【LeetCode】506. Relative Ranks

运动员成绩排名与奖牌分配算法
本文介绍了一种算法,用于处理一组运动员的成绩,并根据成绩分配相应的奖牌(金牌、银牌、铜牌),同时为其他运动员分配相对排名。算法通过使用HashMap存储成绩和位置,再进行排序,最后遍历数组将位置改为对应的排名或奖牌。

题目:
Given scores of N athletes, find their relative ranks and the people with the top three highest scores, who will be awarded medals: “Gold Medal”, “Silver Medal” and “Bronze Medal”.

Example 1:
Input: [5, 4, 3, 2, 1]
Output: [“Gold Medal”, “Silver Medal”, “Bronze Medal”, “4”, “5”]
Explanation: The first three athletes got the top three highest scores, so they got “Gold Medal”, “Silver Medal” and “Bronze Medal”.
For the left two athletes, you just need to output their relative ranks according to their scores.

思路:
这道题题目我又看了半天,这个例子太有迷惑性了。这个数组是乱序的,然后你要按照大小给他们赋值,金银铜,和排名,不能改变顺序。。。
这种不能改变顺序的一般思路都是用hashmap存值和位置,然后再sort,遍历的时候如果对应到相对的值就把位置改成对应的排名。
写两个数组倒叙遍历就可以考虑到前三个是金银铜了。
然后String转换成int的方法就是“ ”+数字

Code:

public String[] findRelativeRanks(int[] nums) {

 Map <Integer,Integer> map = new HashMap<Integer,Integer>();
 int len = nums.length;
    
 for(int i=0;i<len;i++){
  map.put(nums[i],i);//value and position   
 }
String [] result = new String[len]; 
String[] res = new String[]{"Gold Medal", "Silver Medal", "Bronze Medal"};     
Arrays.sort(nums);

for(int i=len-1;i>=0;i--){
  if(i>=len-3){
      result[map.get(nums[i])]=res[len-i-1];
  }else
      result[map.get(nums[i])]=""+(len-i);
}
return result;    
    
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值