506. 相对名次https://leetcode.cn/problems/relative-ranks/
难度简单180收藏分享切换为英文接收动态反馈
给你一个长度为 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 <= 104
0 <= score[i] <= 106
score
中的所有值 互不相同
通过次数65,965提交次数101,240
class Solution {
public String[] findRelativeRanks(int[] score) {
if(score.length==1) return new String[]{"Gold Medal"};
// 解法:先排序 使用hashMap 然后在从hashmap里取值
int[] nums = new int[score.length];
for(int i=0;i<score.length;i++) nums[i] = score[i];
// 排序:冒泡排序:
for(int i=1;i<nums.length;i++)
{
int flag = 1;
for(int j=0;j<nums.length-i;j++)
{
if(nums[j]<nums[j+1])
{
int temp = nums[j];
nums[j] = nums[j+1];
nums[j+1] = temp;
flag = 0;
}
}
if(flag ==1) break;
}
HashMap<Integer,String> ans = new HashMap<Integer,String>();
if(score.length>=0) ans.put(nums[0],"Gold Medal");
if(score.length>=1) ans.put(nums[1],"Silver Medal");
if(score.length>2) ans.put(nums[2],"Bronze Medal");
for(int i=3;i<nums.length;i++)
{
ans.put(nums[i],(i+1)+"");
}
String[] ans1 = new String[score.length];
for(int i=0;i<score.length;i++)
{
ans1[i] = ans.get(score[i]);
}
return ans1;
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/69033.html