leetcode-167-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.

Input: numbers={2, 7, 11, 15}, target=9
Outputi: index1=1, index2=2

分析


这道题其实和 3Sum 的思路一样,设置一前一后两个指针即可。时间复杂度是$O(n)$,空间复杂度是$O(1)$

解决方案1(C++)


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
public:
vector<int> twoSum(vector<int>& numbers, int target) {
vector<int> res(2, -1);
int left = 0;
int right = numbers.size() - 1;
while(left < right) {
int tmp = numbers[left] + numbers[right];
if(tmp == target) {
res[0] = left + 1;
res[1] = right + 1;
return res;
}else if(tmp < target) {
left++;
}else {
right--;
}
}
return res;
}
};

解决方案2(Python)


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution(object):
def twoSum(self, numbers, target):
"""
:type numbers: List[int]
:type target: int
:rtype: List[int]
"""
result = [-1, -1]
left = 0
right = len(numbers) - 1
while left < right:
# print right
tmp = numbers[left] + numbers[right]
if tmp == target:
result[0] = left + 1
result[1] = right + 1
return result
elif tmp < target:
left += 1
else:
right -= 1

return result

相关问题


题目来源