Skip to content

506. Relative Ranks 👍

  • Time: $O(\texttt{sort})$
  • Space: $O(n)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class Solution {
 public:
  vector<string> findRelativeRanks(vector<int>& nums) {
    const int n = nums.size();
    vector<string> ans(n);
    vector<int> indices(n);

    iota(indices.begin(), indices.end(), 0);

    ranges::sort(indices,
                 [&](const int a, const int b) { return nums[a] > nums[b]; });

    for (int i = 0; i < n; ++i)
      if (i == 0)
        ans[indices[0]] = "Gold Medal";
      else if (i == 1)
        ans[indices[1]] = "Silver Medal";
      else if (i == 2)
        ans[indices[2]] = "Bronze Medal";
      else
        ans[indices[i]] = to_string(i + 1);

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution {
  public String[] findRelativeRanks(int[] nums) {
    final int n = nums.length;
    String[] ans = new String[n];
    List<Integer> indices = new ArrayList<>();

    for (int i = 0; i < n; ++i)
      indices.add(i);

    Collections.sort(indices, (a, b) -> Integer.compare(nums[b], nums[a]));

    for (int i = 0; i < n; ++i)
      if (i == 0)
        ans[indices.get(0)] = "Gold Medal";
      else if (i == 1)
        ans[indices.get(1)] = "Silver Medal";
      else if (i == 2)
        ans[indices.get(2)] = "Bronze Medal";
      else
        ans[indices.get(i)] = String.valueOf(i + 1);

    return ans;
  }
}