原题如下:
1635. Max Pair
Give two Lists, give a maximum value, find a bunch in each of the two lists, and find all the pairs that are closest to the maximum but not larger than the maximum.
Example
Give a=[2,3,4,5,6], b=[4,5,7], x=8’, return [[3,5],[4,4]].
Explanation:
the sum of [3,5] or [4,4] is 8, which is no larger than 8.
Give a=[2,3,4,5,6], b=[4,5,7], x=10’, return [[3,7],[5,5],[6,4]].
Explanation:
the sum of [3,7],[5,5],[6,4] is 10, which is no larger than 10.
Notice
The length of the two lists do not exceed 100000100000.
Each element do not exceed 10000000001000000000.
解法1:
用Binary Search。我的方法较慢。
class Solution {
public:
/**
* @param a: the first list
* @param b: the second list
* @param x: the max sum
* @return: the pairs whose sum are not exceed x
*/
vector<vector<int>> getAns(vector<int> &a1, vector<int> &b1, int x) {
set<int> sa(a1.begin(), a1.end());
set<int> sb(b1.begin(), b1.end());
a1.assign(sa.begin(), sa.end());
b1.assign(sb.begin(), sb.end());
vector<vector<int>> result;
int maxSum = INT_MIN;
bool targetFind = false;
for (auto n : a1) {
std::vector<int>::iterator lowIt = std::lower_bound(b1.begin(), b1.end(), x - n);
if ((lowIt!= b1.begin()) && ((n + *lowIt) > x)) lowIt--; //as *lowIt >= (x-n)
int m = *lowIt;
int sum = n + m;
if (sum > x)
continue;
else if (sum == x) {
if (maxSum < sum) {
result = {};
maxSum = sum;
}
targetFind = true;
result.push_back({n, m});
} else if (!targetFind) {
if (sum > maxSum) {
result = {};
maxSum = sum;
result.push_back({n, m});
}
}
}
return result;
}
};