题目描述:
给定两个大小相等的数组 A 和 B,A 相对于 B 的优势可以用满足 A[i] > B[i] 的索引 i 的数目来描述。
返回 A 的任意排列,使其相对于 B 的优势最大化。
示例 1:
输入:A = [2,7,11,15], B = [1,10,4,11]
输出:[2,11,7,15]
示例 2:
输入:A = [12,24,8,32], B = [13,25,32,11]
输出:[24,32,8,12]
提示:
1 <= A.length = B.length <= 10000
0 <= A[i] <= 10^9
0 <= B[i] <= 10^9
方法1:
主要思路:解题链接汇总
(1)使用 map<int,int>对数组A的元素进行统计;
(2)然后使用贪心,每次对B的元素在A的map中找第一个大于该元素的位置,可以使用upper_bound实现,若找到,则使用该值,若找不到,则使用map中的第一个值,既最小值;
(3)同时更新每个元素的数量,当数量为0时,在map中删除该结点;
class Solution {
public:
vector<int> advantageCount(vector<int>& A, vector<int>& B) {
map<int,int> mp;
for(int&a:A){//统计
++mp[a];
}
vector<int>res(A.size());//存储结果
for(int i=0;i<B.size();++i){
auto it=mp.upper_bound(B[i]);//找第一个大于该值的结点
if(it==mp.end()){//若没找到
res[i]=mp.begin()->first;//使用map中的最小值
if(mp.begin()->second==1){//更新结点
mp.erase(mp.begin());
}
else{
--(mp.begin()->second);
}
}
else{
res[i]=it->first;//若找到了,则使用该值
if(it->second==1){
mp.erase(it);
}
else{
--(it->second);
}
}
}
return res;
}
};