Given an array of integers that is already sorted in ascending order, find two numbers such that they add up to a specific target number.
The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.
You may assume that each input would have exactly one solution and you may not use the same element twice.
Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2
思路:
1.扫描已经排好序的数组,扫描的数据保存在字典中,并判断需要成对的另一个数是否在数组中;
2.双指针向中心移动;
由于数组为有序数组,因此利用头尾指针进行处理,头尾元素之和大于目标值,尾指针向前移动, 如果大于目标值,首指针向后移动
# 利用字典保留已经扫描过的历史数据 class Solution(): def twoSum(self, numbers, target): """ :type numbers: List[int] :type target: int :rtype: List[int] """ dic = {} for i, num in enumerate(numbers): if (target - num) in dic: return [dic[target - num], i + 1] dic[num] = i + 1
# 双指针 class Solution(): def twoSum(self, numbers, target): """ :type numbers: List[int] :type target: int :rtype: List[int] """ left, right = 0, len(numbers) - 1 while left < right: if numbers[left] + numbers[right] == target: return [left + 1, right + 1] elif numbers[left] + numbers[right] > target: right -= 1 else: left += 1