leetcode 506. Relative Ranks
Given scores of N athletes, find their relative ranks and the people with the top three highest scores, who will be awarded medals: "Gold Medal", "Silver Medal" and "Bronze Medal".
Example 1:
Input: [5, 4, 3, 2, 1] Output: ["Gold Medal", "Silver Medal", "Bronze Medal", "4", "5"] Explanation: The first three athletes got the top three highest scores, so they got "Gold Medal", "Silver Medal" and "Bronze Medal".
For the left two athletes, you just need to output their relative ranks according to their scores.
Note:
- N is a positive integer and won't exceed 10,000.
- All the scores of athletes are guaranteed to be unique.
class Solution(object): def findRelativeRanks(self, nums): """ :type nums: List[int] :rtype: List[str] """ # find pos of num in sorted nums # use hashmap to record number pos sorted_nums = sorted(nums, reverse=True) pos_map = {n:i for i,n in enumerate(sorted_nums)} def find_pos(n): top3 = ("Gold Medal", "Silver Medal", "Bronze Medal") if n < 3: return top3[n] else: return str(n+1) return [find_pos(pos_map[n]) for n in nums]
class Solution(object): def findRelativeRanks(self, nums): """ :type nums: List[int] :rtype: List[str] """ sort = sorted(nums, reverse=True) rank = ["Gold Medal", "Silver Medal", "Bronze Medal"] + map(str, range(4, len(nums) + 1)) return map(dict(zip(sort, rank)).get, nums)
no use map solution:
class Solution(object): def findRelativeRanks(self, nums): """ :type nums: List[int] :rtype: List[str] """ pos_arr = [(i, n) for i,n in enumerate(nums)] pos_arr.sort(key=lambda x: x[1], reverse=True) ans = range(0, len(nums)) top3 = ["Gold Medal", "Silver Medal", "Bronze Medal"] for rank in range(0, len(nums)): pos = pos_arr[rank][0] if rank < 3: ans[pos] = top3[rank] else: ans[pos] = str(rank+1) return ans
标签:
leetcode
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· DeepSeek 开源周回顾「GitHub 热点速览」
2017-04-01 信息检索导论的课件——http://home.ustc.edu.cn/~zhufengx/ir/pdf/
2017-04-01 通过Mesos、Docker和Go,使用300行代码创建一个分布式系统
2017-04-01 varint算法——本质上是牺牲最高位作为标识数据结束位,达到变长编码,说白了就是贪心的分割位