888. 公平的糖果棒交换
分类:数组
排序后二分
class Solution {
public:
int binarySearch(vector<int>& B, int t){
int l=0, r=B.size();
while(l<r){
int mid = (l+r) >> 1;
if(B[mid] > t){
r = mid;
}else if(B[mid] < t){
l = mid+1;
}else{
return mid;
}
}
return -1;
}
vector<int> fairCandySwap(vector<int>& A, vector<int>& B) {
int sum1 = accumulate(A.begin(), A.end(), 0);
int sum2 = accumulate(B.begin(), B.end(), 0);
sort(B.begin(), B.end());
int avg = (sum1 + sum2) / 2 ;
for(int i=0; i<A.size(); i++){
// a[i] + sum2 - b[j] == avg 则交换后相等
int j = binarySearch(B, A[i]+sum2-avg);
if(j!=-1){
return {A[i], B[j]};
}
}
return {0, 0};
}
};/* 99% **/
2021/02/01