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
JavaScript utilizes a Map
to store the rank information derived from sorted scores. By iterating through the original scores and utilizing this map, we can efficiently assign the rank or medal string to each position in the result, simplifying complexity handling.