欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

LeetCode870. 优势洗牌(贪心算法) Python实现

程序员文章站 2024-02-13 14:00:10
...

LeetCode870. 优势洗牌(贪心算法)

LeetCode870. 优势洗牌(贪心算法) Python实现

贪心策略: 田忌赛马


  • code

class Solution:
    def advantageCount(self, A: list, B: list) -> list:
        l = len(A)
        ans = [0 for _ in range(l)]
        b = sorted(list(range(l)), key=(lambda x: B[x]))
        a = sorted(A)
        s, e = 0, l - 1
        for i in range(l):
            if a[i] > B[b[s]]:
                ans[b[s]] = a[i]
                s += 1
            else:
                ans[b[e]] = a[i]
                e -= 1
        return ans

# test
if __name__ == '__main__':
    s = Solution()
    a = [2,0,4,1,2]
    b = [1,3,0,0,2]
    print(s.advantageCount(a,b))
   
  • result
[2, 0, 1, 2, 4]