leetcode:506.相对名次

题目

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/relative-ranks

给你一个长度为 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 位运动员的获奖情况。

示例 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 <= 1 0 4 10^4 104
0 <= score[i] <= 1 0 6 10^6 106
score 中的所有值 互不相同

解法

  • 该题目是一个排序问题,难点是需要映射好排序后原始元素所处的index,然后将对应的index替换成相应的文本数据。
  • 解题思路:
    • 排序+哈希: 使用哈希来记录原始元素的index,然后使用排序算法从大到小排序,找到对应元素的index替换成对应的文本即可。

排序+哈希

  • python
class Solution:
    def findRelativeRanks(self, score: List[int]) -> List[str]:
        ranks = sorted(score, reverse=True)
        ranksIndex = {
    
    }
        for i in range(len(ranks)):
            print(ranks[i])
            ranksIndex[ranks[i]] = i
        ans = []
        for s in score:
            rank = ranksIndex[s]
            if rank == 0:
                ans.append("Gold Medal")
            elif rank == 1:
                ans.append("Silver Medal")
            elif rank == 2:
                ans.append("Bronze Medal")
            else:
                ans.append(str(rank+1))
        return ans
  • c++
class Solution {
public:
    vector<string> findRelativeRanks(vector<int>& score) {
        int n = score.size();
        vector<string> ans(n);
        string desc[3] = {"Gold Medal", "Silver Medal", "Bronze Medal"};

        vector<pair<int, int>> arr;
        for(int i=0; i<n; i++)
        {
            arr.emplace_back(-score[i], i);  // 转成负数后,从小到大即为从大到小
            // arr.push_back(make_pair(-score[i], i))
        }
        sort(arr.begin(), arr.end());

        for(int i=0; i<n; i++)
        {
            if(i>=3)
            {
                ans[arr[i].second] = to_string(i+1);
            }
            else
            {
                ans[arr[i].second] = desc[i];
            }
        }
        return ans;
    }
};
    }
};

复杂度分析

  • 时间复杂度:
    • O ( N ∗ l o g N ) O(N*logN) O(NlogN) 排序花费的时间
  • 空间复杂度:
    • O ( N ) O(N) O(N)

参考

猜你喜欢

转载自blog.csdn.net/uncle_ll/article/details/121689243
今日推荐