1 Description
506. Relative ranking
Give you a lengthn
array of integersscore
,inscore[i]
Yesi
Athlete scored in the competition. All scoresDifferent from each other 。
Athletes will score based onDecide the ranking, among them1
The athletes score the highest score and ranked2
Athlete scored2
High, and so on. The ranking of athletes determines their winning status:
- The athlete ranked 1 won the gold medal "Gold Medal".
- The second-ranked athlete won the silver medal "Silver Medal".
- The athlete ranked third won the bronze medal "Bronze Medal".
- Athletes from 4th to nth can only get their ranking number (i.e., athletes from 4th to 1st place get their number "x").
Use an array of length n answer to return the award, where answer[i] is the award status of the i-th athlete.
Example 1:
enter:score = [5,4,3,2,1] Output:["Gold Medal","Silver Medal","Bronze Medal","4","5"] explain:Ranking is [1st, 2nd, 3rd, 4th, 5th] 。
Example 2:
enter:score = [10,3,8,9,4] Output:["Gold Medal","5","Bronze Medal","Silver Medal","4"] explain:Ranking is [1st, 5th, 3rd, 2nd, 4th] 。
hint:
n ==
1 <= n <= 10^4
0 <= score[i] <= 10^6
All values in score are different
Two Analysis
This question is solved by map mapping. First, all strings are added to the specified map set, and the corresponding index is given in turn. Then, the string array is sorted from large to small, and the value is found from the map set by keys in turn, and the value is given to the string array created in advance as an index. From large to small, it is assigned to "Gold Medal", "Silver Medal", "Bronze Medal" and 3, 4, and 5...
Three Answers
class Solution { public String[] findRelativeRanks(int[] nums) { if(==1) { return new String[]{"Gold Medal"}; } String[] arr = new String[]; Map<Integer,Integer> map = new HashMap<Integer,Integer>(); int count = 0; for(int i = 0,j=0;i< && j<;i++,j++) { (nums[i],j); } (nums); for(int i = 0;i</2;i++) { int temp = nums[-i-1]; nums[-i-1] = nums[i]; nums[i] = temp; } if(==2) { arr[(nums[0])] = "Gold Medal"; arr[(nums[1])] = "Silver Medal"; return arr; } arr[(nums[0])] = "Gold Medal"; arr[(nums[1])] = "Silver Medal"; arr[(nums[2])] = "Bronze Medal"; for(int i = 3;i<;i++) { arr[(nums[i])] = i+1+""; } return arr; } }
The above is the detailed explanation of the relative ranking example of the go language problem solution LeetCode506. For more information about the relative ranking of go language problem solution, please pay attention to my other related articles!