题目:
Given an array A
of integers and integer K
, return the maximum S
such that there exists i < j
with A[i] + A[j] = S
and S < K
. If no i, j
exist satisfying this equation, return -1.
Example 1:
Input: A = [34,23,1,24,75,33,54,8], K = 60 Output: 58 Explanation: We can use 34 and 24 to sum 58 which is less than 60.
Example 2:
Input: A = [10,20,30], K = 15 Output: -1 Explanation: In this case it's not possible to get a pair sum less that 15.
Note:
1 <= A.length <= 100
1 <= A[i] <= 1000
1 <= K <= 2000
这道题是求数组中两个数相加之和小于且最接近一个数字,和2sum也是类似的,上来直接想到的就是排序后双指针的做法。start和end加起来(sum)如果小于这个数,则判断sum和之前所加过的最大值(result)谁大就让result是谁,并且把start往后挪;如果sum比这个数大,则需要把end逐渐往前挪。时间复杂度O(n),空间复杂度O(1)。
Runtime: 1 ms, faster than 100.00% of Java online submissions for Two Sum Less Than K.
Memory Usage: 38.1 MB, less than 33.33% of Java online submissions for Two Sum Less Than K.
class Solution {
public int twoSumLessThanK(int[] A, int K) {
Arrays.sort(A);
int pStart = 0;
int pEnd = A.length - 1;
int result = -1;
while (pStart < pEnd) {
int sum = A[pStart] + A[pEnd];
if (sum < K) {
result = Math.max(sum, result);
pStart++;
} else {
pEnd--;
}
}
return result;
}
}
另外还看到一个用TreeSet的方法的,大概思路是用TreeSet来存放数组中的数,遍历数组的时候先从treeset中采用lower()函数来找出可以与当前元素相加比K小的最大数,然后判断这个treeset里的数和当前遍历的数加起来是不是比之前的结果大。代码就不写了,链接在这儿:https://leetcode.com/problems/two-sum-less-than-k/discuss/323095/Java-solution-using-TreeSet