leecode第13天

506.相对名次
# 给你一个长度为 n 的整数数组 score ,其中 score[i] 是第 i 位运动员在比赛中的得分。所有得分都 互不相同 。

# 运动员将根据得分 决定名次 ,其中名次第 1 的运动员得分最高,名次第 2 的运动员得分第 2 高,依此类推。运动员的名次决定了他们的获奖情况:

# 名次第 1 的运动员获金牌 "Gold Medal" 。
# 名次第 2 的运动员获银牌 "Silver Medal" 。
# 名次第 3 的运动员获铜牌 "Bronze Medal" 。
# 从名次第 4 到第 n 的运动员,只能获得他们的名次编号(即,名次第 x 的运动员获得编号 "x")。
# 使用长度为 n 的数组 answer 返回获奖,其中 answer[i] 是第 i 位运动员的获奖情况。
import copy
class Solution(object):
    def findRelativeRanks(self, score):
        """
        :type score: List[int]
        :rtype: List[str]
        """
        answer=score
        #lo=[]
        #while len(lo)<len(answer):
        #    lo.append(answer.index(max(answer)))
        #    answer[answer.index(max(answer))]=-1
        # 使用排序代替多次查找最大值
    	lo = sorted(range(len(score)), key=lambda i: score[i], reverse=True)

        res=[]
        for i in range(len(lo)):
            res.append(-1)

        for i in range(len(lo)):
            if i==0:
                res[lo[i]]="Gold Medal"
            elif i==1:
                res[lo[i]]="Silver Medal"
            elif i==2:
                res[lo[i]]="Bronze Medal"
            else:
                res[lo[i]]=str(i+1)

        return res

问题分析与优化建议

1. 潜在问题
  • 修改输入数据:代码中直接修改了输入参数 score,将其元素设置为 -1。这可能会导致原始输入数据被破坏,不符合函数设计的原则(输入应保持不变)。
  • 效率低下:通过多次调用 max()index() 来找到最大值及其索引,时间复杂度为 (O(n^2)),对于较大的输入列表性能较差。
  • 异常处理缺失:未对输入进行校验,例如 score 是否为空、是否包含非数字等。
  • 冗余逻辑res 列表初始化为 -1 后又重新赋值,这部分逻辑可以简化。
2. 优化方向
  • 避免修改输入:通过复制输入数据来避免直接修改原始列表。
  • 提高效率:使用排序代替多次查找最大值的操作,将时间复杂度降低到 (O(n \log n))。
  • 增强可维护性:通过字典映射奖牌名称,减少重复的条件判断。
  • 输入校验:增加对输入的合法性检查,确保函数的健壮性。
def findRelativeRanks(self, score):
    """
    :type score: List[int]
    :rtype: List[str]
    """
    # 输入校验
    if not score or any(not isinstance(x, (int, float)) for x in score):
        raise ValueError("Input must be a non-empty list of numbers")

    # 使用排序代替多次查找最大值
    sorted_indices = sorted(range(len(score)), key=lambda i: score[i], reverse=True)

    # 奖牌名称映射
    medal_map = {
        0: "Gold Medal",
        1: "Silver Medal",
        2: "Bronze Medal"
    }

    # 初始化结果列表
    res = [""] * len(score)

    # 根据排名填充结果
    for rank, index in enumerate(sorted_indices):
        res[index] = medal_map.get(rank, str(rank + 1))

    return res
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值