zoukankan      html  css  js  c++  java
  • 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;
        }
    }
  • 相关阅读:
    自动化部署功
    docker 安装
    批量操作
    centos7 内核升级
    centos 6.5 升级 内核
    如何进行再linux 下查看 java程序的堆栈信息
    binlog 日志恢复以及操作
    java 中 Integer 比较 问题
    docker 使用
    soucetree 安装
  • 原文地址:https://www.cnblogs.com/fatttcat/p/13959611.html
Copyright © 2011-2022 走看看