LeetCode-506. Relative Ranks (Java)

来源:互联网 发布:瑶知天上桂花孤的意思 编辑:程序博客网 时间:2024/06/10 12:41

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.

Note:

  1. N is a positive integer and won't exceed 10,000.
  2. All the scores of athletes are guaranteed to be unique.

-------------------------------------------------------------------------------------------------------------------------------------------

题意

有N个运动员排成一列,他们各自有不同的分数,现在需要给这一列的运动员进行排名,前三名给颁发金银铜牌,其他只是对其排名。

他们在这一列的位置需要保持不变。

思路

首先这是一整数数组排序问题,然后就想到之前那种方法,将原数组的值作为新数组的索引实现排序。然后以这种方法为出发点,

完善代码,实现需求。

使用同样方法之题目一

使用同样方法之题目二

使用同样方法之题目三

代码

public class Solution {    public String[] findRelativeRanks(int[] nums) {        //找到原数组中最大的值,因为新数组需要以原数组的值为索引        //在新数组初始化时需要知道这个最大值        int maxIndex = 0;        for(int value : nums){        if(value > maxIndex){        maxIndex = value;        }        }        //初始化新数组        int[] newNums = new int[maxIndex+1];        //以原数组的值作为索引,以原数组的索引作为值        for(int i = 0; i < nums.length;i++){            //因为newsNums中是一个稀疏数组,未赋值的默认为0            //在此i+1是为了将原数组0位置的元素与默认0区分,            //表示运动员在原数组的位置        newNums[nums[i]] = i+1;        }        //用来得到newNums中有意义有值的元素个数        int noNullCount = 0;        for(int i=0;i<newNums.length;i++){        if(newNums[i]==0) continue;        noNullCount++;        }        //用noNullCount初始化result数组        String[] result = new String[noNullCount];        //此resultCount用来统计排名。        int resultCount = 1;        //此count用来统计前三名是否已经颁发奖牌        int count =0;        for(int i=newNums.length-1; i >=0;i--){        if( newNums[i] ==0){        continue;        }        //判断前三名是否已经颁发完毕        if(count <3){        if(count ==0){        count++;        resultCount++;        result[newNums[i]-1] = "Gold Medal";        continue;        }        if(count ==1){        count++;        resultCount++;        result[newNums[i]-1] = "Silver Medal";        continue;        }        if(count ==2){        count++;        resultCount++;        result[newNums[i]-1] = "Bronze Medal";        continue;        }        }        else{            //newNums[i]的值为运动员在队列中的位置,resultCount为名次        result[newNums[i]-1] = resultCount+"";        resultCount++;        }        }                return result;    }}


原创粉丝点击