167. 两数之和 II - 输入有序数组
双指针
class Solution { public int[] twoSum(int[] numbers, int target) { if(numbers.length < 2) return null; int i = 0, j = numbers.length - 1; while(i < j){ if(numbers[i] + numbers[j] < target){ i++; }else if(numbers[i] + numbers[j] > target){ j--; }else return new int[]{i + 1, j + 1}; } return null; } }
python
class Solution: def twoSum(self, numbers: List[int], target: int) -> List[int]: i, j = 0, len(numbers) - 1 while i < j : if numbers[i] + numbers[j] < target: i += 1 elif numbers[i] + numbers[j] > target: j -= 1 else: return [i + 1, j + 1] return [-1, -1]