-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path888.公平的糖果交换.cpp
executable file
·60 lines (56 loc) · 1.7 KB
/
888.公平的糖果交换.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
/*
* @lc app=leetcode.cn id=888 lang=cpp
*
* [888] 公平的糖果交换
*/
// @lc code=start
class Solution {
public:
vector<int> fairCandySwap(vector<int>& A, vector<int>& B) {
unordered_set<int> s;
int sum = 0, s1;
for(int it : A) sum += it;
s1 = sum;
for(int it : B) sum += it, s.insert(it);
sum /= 2;
int n = sum - s1;
for(int it : A) {
// s1 - it + x == sum
if(s.find(n + it) != s.end()) return {it, n + it};
}
return {};
}
// // 二分法
// vector<int> fairCandySwap(vector<int>& A, vector<int>& B) {
// sort(A.begin(),A.end());
// sort(B.begin(),B.end());
// int sumA = 0, sumB = 0;
// for(int i = 0;i < A.size() || i < B.size(); ++i){
// if(i < A.size())
// sumA += A[i];
// if(i < B.size())
// sumB += B[i];
// }
// // sumA - A[i] + B[j] = sumB - B[j] + A[i]
// // sumA - 2 * A[i] = sumB - 2 * B[j]
// int aa,bb;
// int left, right, mid;
// for(int i = 0; i < A.size(); ++i){
// aa = sumA - 2 * A[i];
// left = 0, right = B.size() - 1;
// while(left <= right){
// mid = (left + right) >> 1;
// bb = sumB - 2 * B[mid];
// if(aa == bb ){
// return {A[i], B[mid]};
// }else if( aa < bb ){
// left = mid+1;
// }else {
// right = mid-1;
// }
// }
// }
// return {-1,-1};
// }
};
// @lc code=end