Sponsored
Sponsored
The idea is to sort the scores but preserve their original indices by pairing each score with its index. Once sorted, we can easily determine their ranks by iterating over the sorted list. We then assign the corresponding rank values based on their positions (i.e., 'Gold Medal' for the first position, etc.). This approach utilizes additional space to maintain the original indices while sorting the scores.
Time Complexity: O(n log n), where n is the number of scores, for the sorting operation.
Space Complexity: O(n) for storing the pair struct array and the result array.
1import java.util.*;
2
3public class Solution {
4 public String[] findRelativeRanks(int[] score) {
5 int n = score.length;
6 String[] result = new String[n];
7 String[] medals = {"Gold Medal", "Silver Medal", "Bronze Medal"};
8
9 int[][] scoreIndex = new int[n][2];
10 for (int i = 0; i < n; i++) {
11 scoreIndex[i][0] = score[i];
12 scoreIndex[i][1] = i;
13 }
14
15 Arrays.sort(scoreIndex, (a, b) -> b[0] - a[0]);
16
17 for (int i = 0; i < n; i++) {
18 if (i < 3) {
19 result[scoreIndex[i][1]] = medals[i];
20 } else {
21 result[scoreIndex[i][1]] = String.valueOf(i + 1);
22 }
23 }
24
25 return result;
26 }
27}
28
In Java, we utilize a 2D array to keep track of both scores and their indices. We sort this array based on scores in descending order using a comparator. The sorted indices help in assigning corresponding rank (medals or number) back to the positions in the original order.
In this approach, we employ a hash map (or dictionary) to map each score to its ranking position in a sorted list. The scores are first sorted to determine order-based ranks. We then iterate through original scores, using the map to quickly assign the appropriate ranking (medal or numeric) to each score.
Time Complexity: O(n log n) from sorting.
Space Complexity: O(n) due to storage of the sorted copy.
1#include <vector>
#include <unordered_map>
#include <algorithm>
using namespace std;
vector<string> findRelativeRanks(vector<int>& score) {
vector<int> sortedScores = score;
unordered_map<int, int> rankMap;
sort(sortedScores.rbegin(), sortedScores.rend());
for (int i = 0; i < sortedScores.size(); ++i) {
rankMap[sortedScores[i]] = i;
}
vector<string> result(score.size());
string medals[] = {"Gold Medal", "Silver Medal", "Bronze Medal"};
for (int i = 0; i < score.size(); ++i) {
int rank = rankMap[score[i]];
if (rank < 3) {
result[i] = medals[rank];
} else {
result[i] = to_string(rank + 1);
}
}
return result;
}
This C++ solution uses a map to store the rank for each score based on a sorted version of the scores. After sorting the scores in descending order, it builds a map of each score to its rank; this allows for quick rank determination directly from the score array by looking up each score in the map.