栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

leetcode(力扣) 506. 相对名次 (哈希表)

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

leetcode(力扣) 506. 相对名次 (哈希表)

题目在这:https://leetcode-cn.com/problems/relative-ranks/

题目分析:

这道题我一开始没看懂,导致做错。。

简单的说一下题目。
给了一个数组 s 。s[i]代表下标为i的人得到的分数.

比如 s[i] = [6,3,9,1] 则 第0号人得分6分,第1号人得分3分,第2号人得分9分,第3号人得分1分
分数越高,排名越高, 所以 这道题应该得到答案(银牌,铜牌,金牌,4)
这里的 4 代表第四名。

思路分析:

如果数组长度小于等于3。则我们直接找到金银铜牌分给他们就行了。

对于长度大于3的数组而言。建立哈希表,key存元素,value存对应下标。
这样我们对元素排序。然后遍历哈希表,由于元素已经有序,且其带着对应的下标,所以可以很轻松的根据索引分金银铜牌和排名。

代码写的异常啰嗦,大家根据上面的思路自行写。。。

仅供参考~

完整代码

class Solution:
    def findRelativeRanks(self, score: List[int]) -> List[str]:
        from collections import Counter

        hash_score = {}

        if len(score) <=3:
            max_ = max(score)
            min_ = min(score)
            if len(score) == 2:
                for j in range(len(score)):
                    if score[j] == max_:
                        score[j] = "Gold Medal"
                    else:
                        score[j] = "Silver Medal"
                return score
            for m in range(len(score)):
                if score[m] == max_:
                    score[m] = "Gold Medal"
                elif score[m] == min_:
                    score[m] = "Bronze Medal"
                else:
                    score[m] = "Silver Medal"
            return score

        for index,key in enumerate(score):
            hash_score[key] = index
        hs = sorted(hash_score.items(),key=lambda x:x[0])
        # 字典排序 按 key排
        score[hs[-1][1]] = "Gold Medal"
        score[hs[-2][1]] = "Silver Medal"
        score[hs[-3][1]] = "Bronze Medal"

        for i in range(len(hs)-4,-1,-1):
            print(hs[i])   # 索引为 hs[i][1]
            score[hs[i][1]] = str(len(score)-i)  # 给当前索引赋值

        return score
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/283823.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号