Leetcode-888 公平的糖果交换
Posted Asurudo Jyo の 倉 庫
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Leetcode-888 公平的糖果交换相关的知识,希望对你有一定的参考价值。
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 };
以上是关于Leetcode-888 公平的糖果交换的主要内容,如果未能解决你的问题,请参考以下文章