LeetCode870. 优势洗牌(贪心算法) Python实现
程序员文章站
2024-02-13 14:00:10
...
LeetCode870. 优势洗牌(贪心算法)
贪心策略: 田忌赛马
-
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]
上一篇: 七夕节
下一篇: LeetCode 870. 优势洗牌