1 题目
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
2 尝试解
2.1 分析
给定一组整数,要求找出不超过K的最大的两数之和。
因为不是等式,无法用hashmap,可以用双指针法。先将数组排序,然后用左右指针前后移动。如果num[left]+num[right] >= K,则将right向左移动,否则将left向右移动。
该方法的思想是,对于右端的每一个数num[right],找到左端最大的num[left],满足num[right]+num[left] < K。
2.2 代码
class Solution {
public:
int twoSumLessThanK(vector<int>& A, int K) {
sort(A.begin(),A.end());
int result = -1;
int left = 0, right = A.size()-1;
while(left < right){
if(A[left]+A[right] < K){
result = max(result,A[left]+A[right]);
left++;
}
else{
right--;
}
}
return result;
}
};
3 标准解
3.1 分析
给定所有数都不小于0,不大于1000,还是可以用unordered_set存储所有的数,对于每一个数i,从K-i-1到0查找这些数是否存在。复杂度为O(K*n)。
3.2 代码