Sunday, October 7, 2018

167. Two Sum II - Input array is sorted

二刷 06/2022

Time O(N)
Space O(1)
Runtime: 2 ms, faster than 68.16% of Java online submissions for Two Sum II - Input Array Is Sorted.
Memory Usage: 49.8 MB, less than 61.71% of Java online submissions for Two Sum II - Input Array Is Sorted.
class Solution {
    public int[] twoSum(int[] numbers, int target) {
        if (numbers == null || numbers.length == 0) {
            return new int[0];
        }
        int left = 0, right = numbers.length - 1;
        while (left < right) {
            int sum = numbers[left] + numbers[right];
            if (sum == target) {
                return new int[]{left + 1, right + 1};
            }
            if (sum < target) {
                left++;
            } else {
                right--;
            }
        }
        return new int[0];
    }
}


一刷
Sorted -> Time O(N)

100.00 %

class Solution {
    public int[] twoSum(int[] numbers, int target) {
        if (numbers == null || numbers.length < 2) {
            return new int[0];
        }
        int left = 0;
        int right = numbers.length - 1;
        int sum = 0;
        while (left < right) {
            sum = numbers[left] + numbers[right];
            if (sum == target) {
                return new int[]{left + 1, right + 1};
            }
            if (sum < target) {
                left++;
            } else {
                right--;
            }
        }
        return new int[0];
    }
}

No comments:

Post a Comment