Leetcode 506. Relative Ranks

Problem

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 1st place athlete’s rank is “Gold Medal”.
  • The 2nd place athlete’s rank is “Silver Medal”.
  • The 3rd place athlete’s rank is “Bronze Medal”.
  • For the 4th place to the nth place athlete, their rank is their placement number (i.e., the xth place athlete’s rank is “x”).

Return an array answer of size n where answer[i] is the rank of the ith athlete.

Algorithm

Construct an array of pairs (id, score), sort it by score, and convert the results into strings according to the definition.

Code

class Solution:
    def findRelativeRanks(self, score: List[int]) -> List[str]:
        ids = list(enumerate(score))
        sorted_scores = sorted(ids, key=lambda x: -x[1])

        ans = [""] * len(score)
        for i, (idi, val) in enumerate(sorted_scores):
            if i == 0:
                ans[idi] = "Gold Medal"
            elif i == 1:
                ans[idi] = "Silver Medal"
            elif i == 2:
                ans[idi] = "Bronze Medal"
            else:
               ans[idi] = str(i+1)
        
        return ans
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值