LeetCode 870. Advantage Shuffle
考点 | 难度 |
---|---|
Greedy | Medium |
题目
You are given two integer arrays nums1 and nums2 both of the same length. The advantage of nums1 with respect to nums2 is the number of indices i for which nums1[i] > nums2[i].
Return any permutation of nums1 that maximizes its advantage with respect to nums2.
思路
sort A和B。对于B里的每一个数,如果大于A里最大的,选最大的,否则选A里最小的。
答案
class Solution(object):
def advantageCount(self, A, B):
n = len(A)
B = sorted([(num, i) for i, num in enumerate(B)])[::-1]
A = sorted(A)[::-1]
ans = [-1]*n
beg, end = 0, n - 1
for num, ind in B:
if A[beg] > num:
ans[ind] = A[beg]
beg += 1
else:
ans[ind] = A[end]
end -= 1
return ans