Advertisement

Python基于哈希表优化查询元素效率

阅读量:
背景

LeetCode 506题:相对名次(https://leetcode-cn.com/problems/relative-ranks/),解决这道题的方法非常直接的核心在于排序算法的应用之后的任务就是要确定排序结果中的各个元素的位置索引

代码优化

一开始写的代码是:

复制代码
    score = [10, 3, 8, 9, 4]
    score_sort = sorted(score, reverse=True)
    res = []
    for s in score:
    loc = score_sort.index(s)
    if loc == 0:
        res.append('Gold Medal')
    elif loc == 1:
        res.append('Silver Medal')
    elif loc == 2:
        res.append('Bronze Medal')
    else:
        res.append(str(loc+1))
    print(res)

可以在AC中获得成功,并且最终结果是正确的

![在这里插入图片描述

全部评论 (0)

还没有任何评论哟~