LeetCode 506: Relative Ranks

Problem Description

Explanation

To solve this problem, we can first create a map to store the scores and their corresponding indices. Then, we can sort the scores in descending order and assign ranks accordingly. Finally, we can update the ranks in the result array based on the original indices.

  • Create a map to store scores and indices.
  • Sort scores in descending order.
  • Assign ranks based on the sorted scores.
  • Update ranks in the result array based on original indices.

Time Complexity: O(n log n) - Sorting the scores Space Complexity: O(n) - Using a map to store scores and indices

Solutions

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

class Solution {
    public String[] findRelativeRanks(int[] score) {
        int n = score.length;
        String[] result = new String[n];
        Map<Integer, Integer> map = new HashMap<>();

        for (int i = 0; i < n; i++) {
            map.put(score[i], i);
        }

        Arrays.sort(score);
        for (int i = 0; i < n; i++) {
            int index = map.get(score[n - i - 1]);
            if (i == 0) {
                result[index] = "Gold Medal";
            } else if (i == 1) {
                result[index] = "Silver Medal";
            } else if (i == 2) {
                result[index] = "Bronze Medal";
            } else {
                result[index] = String.valueOf(i + 1);
            }
        }

        return result;
    }
}

Loading editor...