Leetcode-888 Fair Candy Swap(公平的糖果交换)

 1 class Solution
 2 {
 3     public:
 4         vector<int> fairCandySwap(vector<int>& A, vector<int>& B)
 5         {
 6             vector<int> result;
 7             int total_A = 0,total_B = 0;
 8             sort(A.begin(),A.end());
 9             sort(B.begin(),B.end());
10             for(auto d:A)
11                 total_A += d;
12             for(auto d:B)
13                 total_B += d;
14 
15             int diff = abs(total_A-total_B)/2;
16             int flag = total_A > total_B ? 1:0;//1 alic 多
17 
18             if(flag)
19             {
20                 for(auto d:A)
21                 {
22                     auto ptr = lower_bound(B.begin(),B.end(),d-diff);
23                     if(ptr!=B.end() && *ptr==d-diff)
24                     {
25                         result.emplace_back(d);
26                         result.emplace_back(d-diff);
27                         return result;
28                     }
29                 }
30             }
31             else
32             {
33                 for(auto d:B)
34                 {
35                     auto ptr = lower_bound(A.begin(),A.end(),d-diff);
36                     if(ptr!=A.end() && *ptr==d-diff)
37                     {
38                         result.emplace_back(d-diff);
39                         result.emplace_back(d);
40                         return result;
41                     }
42                 }
43             }
44             return result;
45         }
46 };

 

posted @ 2018-08-19 11:05  Asurudo  阅读(552)  评论(0编辑  收藏  举报