506.较名次(javascript)506.RelativeRanks

原创
小哥 3年前 (2022-11-10) 阅读数 2 #大杂烩

给你一个长度 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 运动员的奖项。

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.

示例 1:

输入:score = [5,4,3,2,1]
输出:["Gold Medal","Silver Medal","Bronze Medal","4","5"]
说明:排名是 [1st, 2nd, 3rd, 4th, 5th] 。

示例 2:

输入:score = [10,3,8,9,4]
输出:["Gold Medal","5","Bronze Medal","Silver Medal","4"]
说明:排名是 [1st, 5th, 3rd, 2nd, 4th] 。

提示:

n == score.length
1 <= n <= 104
0 <= score[i] <= 106
score 中的所有值 互不相同

解决问题的思路:
首先,你怎么知道运动员的排名?你需要按降序排列分数,并根据分数进行匹配。score在这个位置上,把他的分数改为他的排名,前三名的特殊待遇

sort原始数组将被更改,因此需要保存排序前的数据。

var findRelativeRanks = function (score) {
    let scoreList = JSON.parse(JSON.stringify(score))
    score.sort((a, b) => {
        return b - a
    })
    for (let i = 0; i < score.length; i++) {
        let index = scoreList.indexOf(score[i])
        //i + 1代表名次
        scoreList[index] = i + 1 + 
        if (i == 0) {
            scoreList[index] = Gold Medal
        } else if (i == 1) {
            scoreList[index] = Silver Medal
        } else if (i == 2) {
            scoreList[index] = Bronze Medal
        }
    }
    return scoreList
};

leetcode: https://leetcode.cn/problems/relative-ranks/

版权声明

所有资源都来源于爬虫采集,如有侵权请联系我们,我们将立即删除