【LeetCode】Two Sum

电玩女神 2022-06-10 05:08 289阅读 0赞

Given an array of integers, return indices of the two numbers such that they add up to a specific target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

  1. Given nums = [2, 7, 11, 15], target = 9,
  2. Because nums[0] + nums[1] = 2 + 7 = 9,
  3. return [0, 1].

我的理解是给定一个列表和一个定值,然后在列表中查找有没有两个数相加等于定值,返回在列表中这两个数的下标
开始我尝试暴力解法,但是py3不支持

  1. class Solution:
  2. def twoSum(self, nums, target):
  3. for i in range(len(nums)):
  4. for j in range(i+1, len(nums)):
  5. if nums[j] == target - nums[i]:
  6. return [i, j]

然后尝试另一种解法

  1. class Solution(object):
  2. def twoSum(self, nums, target):
  3. """
  4. :type nums: List[int]
  5. :type target: int
  6. :rtype: List[int]
  7. """
  8. if len(nums)<=1:
  9. return False
  10. for i in range(len(nums)):
  11. m=target-nums[i]
  12. if m in nums:
  13. mIndex=nums.index(m)
  14. if mIndex==i:
  15. i+=i
  16. else:
  17. return [i,mIndex]

成功!

发表评论

表情:
评论列表 (有 0 条评论,289人围观)

还没有评论,来说两句吧...

相关阅读

    相关 3Sum

    [原题链接][Link 1] 给一个拥有n个元素的数组S,S中是否会有a,b,c三个元素使得a+b+c=0?寻找出满足该条件的所有唯一三元组。 Note: 答案中必须不

    相关 Sum

    你的任务是求出在1到N之间额所有整数的总和。 输入: 输入是一个绝对值不大于10000的整数N。 输出: 输出一个整数,是所有在1到N之间的整数之和。 inc