题目:
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
思路:
变量:sortedA---->表示重新排列后的A的元素
sortedB----->表示重新排列后的B序列
assgined------>表示关联元素
remaining----->A中没有优点的元素
贪心法:对于sortedA中的元素a<=b(当前B中最小值),则a在b中找不到比它差的元素,那就把它扔到垃圾桶里面,否则就将a安置下来
python code:
def advantageCount(self, A: ‘List[int]’, B: ‘List[int]’) -> ‘List[int]’:
assigned={b:[] for b in B}
sortedB,sortedA,remaining=sorted(B),sorted(A),[]
j=0
for a in sortedA:
if a>sortedB[j]:
assigned[sortedB[j]].append(a)
j+=1
else:
remaining.append(a)
return [assigned[b].pop() if assigned[b] else remaining.pop() for b in B]
c++ 版本:
vector advantageCount(vector& A, vector& B) {
multiset s(begin(A), end(A));
for (auto i = 0; i < B.size(); ++i) {
auto p = *s.rbegin() <= B[i] ? s.begin() : s.upper_bound(B[i]);
A[i] = *p;
s.erase§;
}
return A;
}