Skip to content

167. 两数之和 II - 输入有序数组

直觉

双向指针,相加<target则左指针往右移,>target则右指针往左移。

java
class Solution {
    public int[] twoSum(int[] numbers, int target) {
        int left = 0, right = numbers.length - 1;
        while (left <= right) {
            int sum = numbers[left] + numbers[right];
            if (sum > target) {
                right--;
            } else if (sum < target) {
                left++;
            } else {
                return new int[] { left + 1, right + 1 };
            }
        }
        return null;
    }
}

基于 MIT 许可发布