LeetCode: 870. Advantage Shuffle
LeetCode: 870. Advantage Shuffle
タイトルの説明
Given two arrays
Example 1:
Example 2:
Note:
問題を解く構想.
ACコード
タイトルの説明
Given two arrays
A
and B
of equal size, the advantage of A
with respect to B
is the number of indices i
for which A[i] > B[i]
. Return any permutation of A
that maximizes its advantage with respect to B
. Example 1:
Input: A = [2,7,11,15], B = [1,10,4,11]
Output: [2,11,7,15]
Example 2:
Input: A = [12,24,8,32], B = [13,25,32,11]
Output: [24,32,8,12]
Note:
1 <= A.length = B.length <= 10000
0 <= A[i] <= 10^9
0 <= B[i] <= 10^9
問題を解く構想.
B
配列の各数字に対応するA
配列の中でその最小値より大きい値を見つけ、そうでなければA
配列の中でデータを処理していない最小値に設定します.ACコード
class Solution {
public:
vector<int> advantageCount(vector<int>& A, vector<int>& B) {
vector<int> ans;
map<int, int> numsACount;
for(int i = 0; i < A.size(); ++i)
{
++numsACount[A[i]];
}
//
for(size_t i = 0; i < B.size(); ++i)
{
int curNum = 0;
auto iter = numsACount.upper_bound(B[i]);
if(iter != numsACount.end())
{
curNum = iter->first;
}
else
{
curNum = numsACount.begin()->first;
}
--numsACount[curNum];
if(numsACount[curNum] == 0) numsACount.erase(curNum);
ans.push_back(curNum);
}
return ans;
}
};