• 1099. Two Sum Less Than K


    ...

    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;
        }
    }
  • 相关阅读:
    进行代码复审训练
    源代码管理工具调查
    软工作业PSP与单元测试训练
    P18 第四题
    开学第一课
    进行代码复审训练
    源代码管理工具调查
    软工 任务2
    软工课后作业01 P18第四题
    课堂作业1--自我介绍
  • 原文地址:https://www.cnblogs.com/fatttcat/p/13959611.html
Copyright © 2020-2023  润新知