1000字范文,内容丰富有趣,学习的好帮手!
1000字范文 > leetcode 506 相对名次

leetcode 506 相对名次

时间:2024-01-09 15:18:46

相关推荐

leetcode 506 相对名次

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

题目

给你一个长度为nnn的整数数组scorescorescore,其中score[i]score[i]score[i]是第iii位运动员在比赛中的得分。所有得分都互不相同

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

名次第 1 的运动员获金牌 “Gold Medal” 。名次第 2 的运动员获银牌 “Silver Medal” 。名次第 3 的运动员获铜牌 “Bronze Medal” 。从名次第 4 到第 n 的运动员,只能获得他们的名次编号(即,名次第 x 的运动员获得编号 “x”)。

使用长度为nnn的数组answeransweranswer返回获奖,其中answer[i]answer[i]answer[i]是第iii位运动员的获奖情况。

示例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] 。

思路1

一个比较基础的排序模拟题,要解决的是一个带下标排序的问题。为此,我们可以构建一个<值,下标>对,然后按值进行排序。这样即使值被打乱了,也可以知道该值原来所对应的下标,从而恢复出每个位置的顺序:

vector<string> findRelativeRanks(vector<int>& score) {int n = score.size();string desc[3] = {"Gold Medal", "Silver Medal", "Bronze Medal"};vector<pair<int, int>> arr;for (int i = 0; i < n; ++i) {arr.emplace_back(make_pair(-score[i], i));}sort(arr.begin(), arr.end());vector<string> ans(n);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;}

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。