算法
(双指针) $O(n)$
利用双指针的做法。 不断移动左指针,调整右指针的位置,直到相等即可。
C++ 代码
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
int l = 0;
int r = nums.size() -1;
while(l < r){
if(nums[l] + nums[r] == target){
vector<int> indexs{l+1,r+1};
return indexs;
} else if(nums[l] + nums[r] > target){
r--;
} else{
l++;
}
}
return vector<int>();
}
};
Java 代码
class Solution {
public int[] twoSum(int[] numbers, int target) {
int left = 0;
int right = numbers.length - 1;
while (left < right) {
if (numbers[left] + numbers[right] == target) {
return new int[] {left + 1, right + 1};
}
else if (numbers[left] + numbers[right] < target) {
left++;
}
else right--;
}
return new int[0];
}
}
Python 代码
class Solution:
def twoSum(self, numbers: List[int], target: int) -> List[int]:
l, r = 0, len(numbers) - 1
while l < r:
value = numbers[l] + numbers[r]
if value == target:
return [l + 1, r + 1]
elif value < target:
l += 1
else: r -= 1
return []