※ 文章網址: https://www.ptt.cc/bbs/Marginalman/M.1715132301.A.C5B.html
Re: [閒聊] 每日leetcode
看板 | Marginalman |
---|---|
作者 | Rushia (早瀬ユウカの体操服 ) |
時間 | 2024-05-08 09:38:19 |
留言 | 0則留言 (0推 0噓 0→) |
https://leetcode.com/problems/relative-ranks/description
506. Relative Ranks
給你一個不重複數字的整數陣列,score[i] 表示第 i 個人的分數,前三個分數高的人分
別是"Gold Medal","Silver Medal","Bronze Medal",第四高的是 4,第五高的是 5,...
求出一個陣列 res, res[i] 表示第 i 個人是什麼獎項。
思路:
1.用 max_heap 依照分數排序,然後遍歷heap,如果是前三個就給他頒獎,不然他就是第
i 名。
py code:
-------------------------------------
class Solution:
def findRelativeRanks(self, score: List[int]) -> List[str]:
n = len(score)
max_heap = []
for i in range(n):
heapq.heappush(max_heap, (-score[i], i))
rank = 4
top_three = ['Bronze Medal', 'Silver Medal', 'Gold Medal']
res = [''] * n
while max_heap:
idx = heapq.heappop(max_heap)[1]
if top_three:
res[idx] = top_three.pop()
else:
res[idx] = str(rank)
rank += 1
return res
-------------------------------------
--
※ 批踢踢實業坊(ptt.cc), 來自: 101.139.48.193 (臺灣)
※ 文章網址: https://www.ptt.cc/bbs/Marginalman/M.1715132301.A.C5B.html
※ 文章網址: https://www.ptt.cc/bbs/Marginalman/M.1715132301.A.C5B.html