7/22 每日一題(回傳運動員分數排名)
You are given an integer array score of size n, where score[i] is the score of the ith athlete in a competition. All the scores are guaranteed to be unique.
The athletes are placed based on their scores, where the 1st place athlete has the highest score, the 2nd place athlete has the 2nd highest score, and so on. The placement of each athlete determines their rank:
- The
1stplace athlete's rank is"Gold Medal". - The
2ndplace athlete's rank is"Silver Medal". - The
3rdplace athlete's rank is"Bronze Medal". - For the
4thplace to thenthplace athlete, their rank is their placement number (i.e., thexthplace athlete's rank is"x").
Return an array answer of size n where answer[i] is the rank of the ith athlete.
Example 1:
Input: score = [5,4,3,2,1] Output: ["Gold Medal","Silver Medal","Bronze Medal","4","5"] Explanation: The placements are [1st, 2nd, 3rd, 4th, 5th].
Example 2:
Input: score = [10,3,8,9,4] Output: ["Gold Medal","5","Bronze Medal","Silver Medal","4"] Explanation: The placements are [1st, 5th, 3rd, 2nd, 4th].
Constraints:
n == score.length1 <= n <= 1040 <= score[i] <= 106- All the values in
scoreare unique.
class Solution:
def findRelativeRanks(self, score: List[int]) -> List[str]:
price=list(range(1,len(score)+1))
#創造符合運動員人數的排名list
price[0]='Gold Medal'
#前三名改成專有獎項
if len(score)>1:
price[1]='Silver Medal'
if len(score)>2:
price[2]='Bronze Medal'
stack=score.copy() #使用stack複製原始得分,留下原始排序
stack.sort(reverse=True)
res={} #初始化字典,紀錄排序後由高到低對應到的獎項
for s,p in zip(stack,price):
res[s]=p
answer=[] #初始化結果list
for i in score:
answer.append(str(res[i]))
#將原始排序對應的獎項加入到ans中
return answer
---------------------參考解答
class Solution:
def findRelativeRanks(self, score: List[int]) -> List[str]:
# 用字典來建立分數和索引的對應關係
score_dict = {score[i]: i for i in range(len(score))}
# 將分數列表降序排序
score.sort(reverse=True)
# 名次列表,用來存儲每個分數的名次
rank = ['Gold Medal', 'Silver Medal', 'Bronze Medal'] + list(map(str, range(4, len(score) + 1)))
# 根據分數列表和名次列表建立分數對應名次的字典
rank_dict = {score[i]: rank[i] for i in range(len(score))}
# 根據原始分數列表得到最終結果
return [rank_dict[s] for s in score_dict]
標籤: leetcode

0 個意見:
張貼留言
訂閱 張貼留言 [Atom]
<< 首頁