题目
给定两个大小相等的数组 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
思路
如果 A 中最小的牌 a 能击败 B 中最小的牌 b,那么我们应当将它们配对。否则, a 将无益于我们的比分,因为它无法击败任何牌。
我们为什么要在 a > b 时将 a 和 b 配对呢?这是因为此时在 A 中的每张牌都比 b 要大,所以不管我们在 b 前面放置哪张牌都可以得分。我们可以用手中最弱的牌来与 b 配对,这样会使 A 中剩余的牌严格地变大,因此会有更多得分点。
代码
class Solution(object):
def advantageCount(self, A, B):
"""
:type A: List[int]
:type B: List[int]
:rtype: List[int]
"""
sortedA= sorted(A)
sortedB= sorted(B)
assign = {b:[] for b in B}
remaining = []
j=0
for x in sortedA:
if x>sortedB[j]:
assign[sortedB[j]].append(x)
j+=1
else:
remaining.append(x)
return [assign[b].pop() if assign[b] else remaining.pop() for b in B ]
A = [12,24,8,32]
B = [13,25,32,11]
sortedA= sorted(A)
sortedB= sorted(B)
assign = {b:[] for b in B}
print(assign)
remaining = []
print(remaining)
j=0
for x in sortedA:
if x>sortedB[j]:
assign[sortedB[j]].append(x)
j+=1
print(assign)
else:
remaining.append(x)
print(remaining)
for b in B:
if assign[b]:
assign[b].pop()
print(assign)
else:
remaining.pop()
print(remaining)
过程
{13: [], 25: [], 32: [], 11: []}
[]
[8]
{13: [], 25: [], 32: [], 11: [12]}
{13: [24], 25: [], 32: [], 11: [12]}
{13: [24], 25: [32], 32: [], 11: [12]}
{13: [], 25: [32], 32: [], 11: [12]}
{13: [], 25: [], 32: [], 11: [12]}
[]
{13: [], 25: [], 32: [], 11: []}