LeetCode

Two Sum II - Input array is sorted

原题:

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.

翻译

大意是给出一个数组(升序)和一个目标数,求数组中的两个数相加正好等于目标数的两个元素的下标

解题思路

left代表左下标,right代表右下标,numbers[left] + numbers[right]如果等于target返回两个下标志分别加一,如果大于target,right左移,否则left右移。
代码实现(java):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class {
public int[] twoSum(int[] numbers, int target) {
int left = 0;
int right = numbers.length - 1;
while(right > left){
int res = numbers[left] + numbers[right];
if(res == target)
return new int[]{left + 1, right + 1};
else if(res < target)
left++;
else
right--;
}
return null;
}
}

代码实现(python):

1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution(object):
def twoSum(self, numbers, target):
left = 0
right = len(numbers) - 1
while(right > left):
res = numbers[left] + numbers[right]
if res == target:
return left + 1, right + 1
elif res < target:
left += 1
else:
right -= 1
return null