Simple Java Solution, with mapping and sorting


  • 0
    J
    public class Solution {
        public String[] findRelativeRanks(int[] nums) {
            Map<Integer,Integer> map = new HashMap<>();
            for(int i = 0; i < nums.length; i++)
                map.put(nums[i],i); // mapping each number to its original index in nums
    
            Arrays.sort(nums); // in-place sorting in ascending order
    
            String[] res = new String[nums.length];
            int j = nums.length;
            for(int i = 0; i < nums.length; i++){
                res[map.get(nums[i])] = Integer.toString(j); // from the lowest score to the highest, write down the ranking according to the mapped index
                if(j == 1) res[map.get(nums[i])] = "Gold Medal";
                if(j == 2) res[map.get(nums[i])] = "Silver Medal";
                if(j == 3) res[map.get(nums[i])] = "Bronze Medal";
                j--;
            }
            return res;
        }
    }
    

    Run time 18ms.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.