【双指针】167.两数之和II—有序数组

题目

class Solution {
    public int[] twoSum(int[] numbers, int target) {
        int[] res = new int[]{-1, -1};
        int left = 0, right = numbers.length - 1;
        while (left < right) {
            if (numbers[left] + numbers[right] == target) {
                res[0] = left + 1;
                res[1] = right + 1;
                break;
            } else if (numbers[left] + numbers[right] < target) {
                // while (left + 1 < right && numbers[left + 1] == numbers[left]) {
                //     ++left;
                // }
                ++left;
            } else {
                // while (right - 1 >= left && numbers[right - 1] == numbers[right]) {
                //     --right;
                // }
                --right;
            }
        }

        return res;
    }
}

你可能感兴趣的:(两数之和)