leetcode 870. 优势洗牌


 

给定两个大小相等的数组 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. 1 <= A.length = B.length <= 10000
  2. 0 <= A[i] <= 10^9
  3. 0 <= B[i] <= 10^9

AC 400ms多 有点慢。。。

class Solution(object):
    def advantageCount(self, A, B):
        """
        :type A: List[int]
        :type B: List[int]
        :rtype: List[int]
        """
        import copy
        AS=copy.deepcopy(A)
        BS=copy.deepcopy(B)
        AS.sort(reverse=True)
        BS.sort()
        res=[None for i in A]
        B_key={}
        for i in range(len(B)):
            if B[i] not in B_key:
                B_key[B[i]]=[]
            B_key[B[i]].append(i)
        for i in AS:
            while 1:
                if not BS:
                    break
                now=BS.pop()
                index=B_key[now].pop()
                if i >now:
                    res[index]=i
                    B[index]=None
                    break
                else:
                    res[index] = AS.pop()
                    B[index] = None
        return res
原文地址:https://www.cnblogs.com/Lynwood/p/9616380.html