Welcome to Subscribe On Youtube
Formatted question description: https://leetcode.ca/all/506.html
506. Relative Ranks
Level
Easy
Description
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:
- N is a positive integer and won’t exceed 10,000.
- All the scores of athletes are guaranteed to be unique.
Solution
Sort the array of scores with the original indices kept. Then for each original index, the rank can be obtained using the index in the sorted array.
-
class Solution { public String[] findRelativeRanks(int[] nums) { int length = nums.length; int[][] scoresIndices = new int[length][2]; for (int i = 0; i < length; i++) { scoresIndices[i][0] = nums[i]; scoresIndices[i][1] = i; } Arrays.sort(scoresIndices, new Comparator<int[]>() { public int compare(int[] array1, int[] array2) { if (array1[0] != array2[0]) return array2[0] - array1[0]; else return array1[1] - array2[1]; } }); String[] ranks = new String[length]; for (int i = 0; i < length; i++) { int index = scoresIndices[i][1]; int rank = i + 1; if (rank == 1) ranks[index] = "Gold Medal"; else if (rank == 2) ranks[index] = "Silver Medal"; else if (rank == 3) ranks[index] = "Bronze Medal"; else ranks[index] = String.valueOf(rank); } return ranks; } }
-
// OJ: https://leetcode.com/problems/relative-ranks/ // Time: O(NlogN) // Space: O(N) class Solution { public: vector<string> findRelativeRanks(vector<int>& A) { int N = A.size(); vector<string> ans(N); vector<int> id(N); iota(begin(id), end(id), 0); sort(begin(id), end(id), [&](int a, int b) { return A[a] > A[b]; }); for (int r = 0; r < N; ++r) { int i = id[r]; if (r < 3) { if (r == 0) ans[i] = "Gold"; else if (r == 1) ans[i] = "Silver"; else ans[i] = "Bronze"; ans[i] += " Medal"; } else ans[i] = to_string(r + 1); } return ans; } };
-
class Solution: def findRelativeRanks(self, score: List[int]) -> List[str]: n = len(score) idx = list(range(n)) idx.sort(key=lambda x: -score[x]) top3 = ['Gold Medal', 'Silver Medal', 'Bronze Medal'] ans = [None] * n for i in range(n): ans[idx[i]] = top3[i] if i < 3 else str(i + 1) return ans ############ class Solution(object): def findRelativeRanks(self, nums): """ :type nums: List[int] :rtype: List[str] """ ans = [""] * len(nums) scores = [] for i, num in enumerate(nums): scores.append((num, i)) scores.sort(reverse=True) rankTitles = ["Gold Medal", "Silver Medal", "Bronze Medal"] rank = 0 for _, i in scores: if rank > 2: ans[i] = str(rank + 1) else: ans[i] = rankTitles[rank] rank += 1 return ans