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

  • java

双指针

class Solution {
    public int[] twoSum(int[] numbers, int target) {
        int n = numbers.length;
        int l = 0, r = n - 1;
        while (l < r) {
            if (numbers[l] + numbers[r] == target) {
                break;
            }
            if (numbers[l] + numbers[r] < target) {
                ++l;
            } else {
                --r;
            }
        }
        return new int[] {l + 1, r + 1};
    }
}

你可能感兴趣的:(LeetCode,java,算法,数据结构)