1099. Two Sum Less Than K - Easy

...

 

M1: sort + two pointers
Push from the two ends and attempt to find any addition of the two elements < K;
if the addition >= K, then decrease the high bound and hence tentatively get a smaller addition;
otherwise, increase low bound to find a bigger addition;
time = O(nlogn), space = O(1)

class Solution {
    public int twoSumLessThanK(int[] A, int K) {
        Arrays.sort(A);
        int max = -1;
        int i = 0, j = A.length - 1;
        while(i < j) {
            if(A[i] + A[j] >= K) {
                j--;
            } else {
                max = Math.max(max, A[i] + A[j]);
                i++;
            }
        }
        return max;
    }
}

 

M2: naive, first sort, then loop the array and for each value A[i]
use binary search to find a value A[j] such that A[i] + A[j] < K
time = O(nlogn), space = O(1)

class Solution {
    public int twoSumLessThanK(int[] A, int K) {
        Arrays.sort(A);
        int max = -1;
        for(int i = 0; i + 1 < A.length; i++) {
            int target = K - A[i];
            int left = i + 1, right = A.length - 1;
            while(left + 1 < right) {
                int mid = left + (right - left) / 2;
                if(A[mid] <= target) {
                    left = mid;
                } else {
                    right = mid;
                }
            }
            if(A[right] < target) {
                max = Math.max(max, A[i] + A[right]);
            } else if(A[left] < target) {
                max = Math.max(max, A[i] + A[left]);
            }
        }
        return max;
    }
}

 

posted @ 2020-11-11 17:06  fatttcat  阅读(116)  评论(0编辑  收藏  举报