看板 Marginalman 關於我們 聯絡資訊
※ 引述《Rushia (早瀬ユウカの体操服 )》之銘言: : 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 : ------------------------------------- 思路:沒有,看圖說故事 C# code public class Solution { public string[] FindRelativeRanks(int[] score) { var pairs = score.Select((s,i) => (s,i)) .OrderByDescending(x => x.s) .ToArray(); var result = new string[score.Length]; if (score.Length >= 1) result[pairs[0].i] = "Gold Medal"; if (score.Length >= 2) result[pairs[1].i] = "Silver Medal"; if (score.Length >= 3) result[pairs[2].i] = "Bronze Medal"; for (int i=3; i<pairs.Length; i++) { result[pairs[i].i] = (i+1).ToString(); } return result; } } -- (づ′・ω・)づ -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 61.220.51.52 (臺灣) ※ 文章網址: https://www.ptt.cc/bbs/Marginalman/M.1715135967.A.5A2.html
DJYOSHITAKA: 大師 05/08 10:40
ILoveErr: 大師 05/08 10:44