# Code language: Python classSolution: deftwoSum(self, nums: List[int], target: int) -> List[int]: n = len(nums) i, j = 1, n while i < j: s = nums[i - 1] + nums[j - 1] if s == target: return [i, j] elif s < target: i += 1 else: j -= 1 return [-1, -1]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
// Code language: Java classSolution { publicint[] twoSum(int[] nums, int target) { for (inti=0, j = nums.length - 1; i < j;) { ints= nums[i] + nums[j]; if (s < target) ++i; elseif (s > target) --j; else returnnewint[] { i + 1, j + 1 }; } returnnewint[] { -1, -1 }; } }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
// Code language: C++ classSolution { public: vector<int> twoSum(vector<int>& nums, int target){ int n = nums.size(); for (int i = 0, j = n - 1; i < j;) { int s = nums[i] + nums[j]; if (s < target) ++i; elseif (s > target) --j; else return vector<int>{i + 1, j + 1}; } return vector<int>{-1, -1}; } };
# Code language: Python classSolution: deftwoSum(self, nums: List[int], target: int) -> List[int]: """双指针 + 二分查找""" n = len(nums) i, j = 0, n - 1 while i < j: s = nums[i] + nums[j] if s > target: left, right = i + 1, j - 1 while left < right: mid = left + right >> 1 ss = nums[i] + nums[mid] if ss > target: right = mid - 1 elif ss < target: left = mid + 1 else: return [i + 1, mid + 1] j = left elif s < target: left, right = i + 1, j - 1 while left < right: mid = left + right >> 1 ss = nums[mid] + nums[j] if ss > target: right = mid - 1 elif ss < target: left = mid + 1 else: return [mid + 1, j + 1] i = left else: return [i + 1, j + 1] return [-1, -1]
// Code language: C++ classSolution { public: vector<int> twoSum(vector<int>& nums, int target){ int n = nums.size(); for (int i = 0, j = n - 1; i < j;) { int s = nums[i] + nums[j]; if (s < target) { int left = i + 1, right = j - 1; while (left < right) { int mid = left + right >> 1; int sum = nums[mid] + nums[j]; if (sum < target) left = mid + 1; elseif (sum > target) right = mid - 1; else return vector<int>{mid + 1, j + 1}; } i = left; } elseif (s > target) { int left = i + 1, right = j - 1; while (left < right) { int mid = left + right >> 1; int sum = nums[i] + nums[mid]; if (sum < target) left = mid + 1; elseif (sum > target) right = mid - 1; else return vector<int>{i + 1, mid + 1}; } j = left; } else return vector<int>{i + 1, j + 1}; } return vector<int>{-1, -1}; } };