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

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

LeetCode870. 优势洗牌(贪心算法) Python实现_第1张图片

贪心策略: 田忌赛马


  • 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]

你可能感兴趣的:(Python,algorithm,贪心)