1. 两数之和

给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。

你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。

示例:

给定 nums = [2, 7, 11, 15], target = 9

因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]


思路:双指针:
  1. 每一趟遍历的前提:i<j;
  2. i指针从前往后,j指针从后往i;
  3. 遇到满足条件的终止遍历并返回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         # 初始化双指针
 9         i, j = 0, len(nums) - 1
10         result = []
11         for i in range(0, len(nums)-1):
12             while i < j:
13                 if i < j and target - nums[i] != nums[j]:
14                     j -= 1
15                 elif i < j and target - nums[i] == nums[j]:
16                     result.append(i)
17                     result.append(j)
18                     return result
19             # 重置j指针:每一趟遍历j均从最后往前走
20             j = len(nums)-1
21             continue
22         return result

 

posted @ 2020-04-11 19:44  人间烟火地三鲜  阅读(172)  评论(0编辑  收藏  举报