CCCPaste

Two Sum (Sorted Input) - LeetCode

// Two Sum - Input Array is sorted - https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/

class Solution {
    // Two pointers
    // Time Complexity: O(n)
    // Space Complexity: O(1)
    public int[] twoSum(int[] numbers, int target) {
        int i = 0, j = numbers.length - 1;

        while(i < j) {
            if(numbers[i] + numbers[j] == target) {
                return new int[]{i+1, j+1};
            }
            else if (numbers[i] + numbers[j] > target) {
                j--;
            } else {
                i++;
            }
        }

        return new int[]{};
        
    }
}