167 Two Sum II - Input array is sorted

1. Question

Given an array of integers that is already sorted in ascending order, find two numbers such that they add up to a specific target number.

The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.

You may assume that each input would haveexactlyone solution and you may not use thesameelement twice.

Input:numbers={2, 7, 11, 15}, target=9 Output:index1=1, index2=2

2. Implementation

(1) Two Pointers

class Solution {
    public int[] twoSum(int[] numbers, int target) {
        int start = 0, end = numbers.length - 1;
        int sum = 0;

        int[] res = new int[2];

        while (start < end) {
            sum = numbers[start] + numbers[end];

            if (sum == target) {
                res[0] = start + 1;
                res[1] = end + 1;
                break;
            }
            else if (sum < target) {
                ++start;
            }
            else {
                --end;
            }
        }
        return res;
    }
}

(2) Two Pointers

class Solution {
    public int[] twoSum(int[] numbers, int target) {
        if (numbers == null || numbers.length == 0) {
            return new int[2];
        }

        int[] res = new int[2];

        for (int i = 0; i < numbers.length; i++) {
            int index = binarySearch(numbers, i + 1, target - numbers[i]);

            if (index != -1) {
                res[0] = i + 1;
                res[1] = index + 1;
                break;
            }
        }
        return res;
    }

    public int binarySearch(int[] numbers, int start, int target) {
        int end = numbers.length - 1, mid = 0;

        while (start <= end) {
            mid = start + (end - start) / 2;

            if (numbers[mid] == target) {
                return mid;
            }
            else if (numbers[mid] < target) {
                start = mid + 1;
            }
            else {
                end = mid - 1;
            }
        }
        return -1;
    }
}

3. Time & Space Complexity

Two Pointers:时间复杂度O(n), 空间复杂度O(1)

Binary Search: 时间复杂度O(logn), 空间复杂度O(1)

Last updated