题目:
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;
}