Two Sum II - Input array is sorted

Given a 1-indexed array of integers numbers that is already sorted in non-decreasing order, find two numbers such that they add up to a specific target number. Let these two numbers be numbers[index1] and numbers[index2] where 1 <= index1 < index2 <= numbers.length.

Return the indices of the two numbers, index1 and index2, added by one as an integer array [index1, index2] of length 2.

The tests are generated such that there is exactly one solution. You may not use the same element twice.

Your solution must use only constant extra space.

My Solutions: 因为Space: O(1), 用two pointers。

    public int[] twoSum(int[] nums, int target) {
        int len = nums.length;
        int sum = 0, l = 0, r = len - 1;
        // 因为此题nums里一定是偶数个数,肯定会找到target,所以直接用l < r 也可以
        // 普通的binary search需要用 l + 1 < r
        while (l < r) {
            sum = nums[l] + nums[r];
            if (sum == target) return new int[]{l + 1, r + 1};
            else if (sum < target) l++;
            else r--;
        }
        return null;
    }

Last updated