LeetCode Solutions

506. Relative Ranks

Time: $O(n\log n)$

Space: $O(n)$

			

class Solution {
 public:
  vector<string> findRelativeRanks(vector<int>& nums) {
    const int n = nums.size();
    vector<string> ans(n);
    vector<int> indices(n);

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

    sort(begin(indices), end(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;
  }
};
			

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) -> 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;
  }
}