Very easy to understand JAVA Solution with detailed explanation. Using Map and Priority Queue


  • 0
    A
    public class Solution {
        public String[] findRelativeRanks(int[] nums) {
            PriorityQueue<Integer> q = new PriorityQueue<>(nums.length,Collections.reverseOrder());
            Map<Integer,String> map = new HashMap<>();
            for (int i=0;i<nums.length;i++)
            {
                q.offer(nums[i]); // Maintains a maxheap
            }
            String[] results = new String[nums.length];
            int i=0;
    //Here , in the below loop the numbers are polled basically based on their decreasing ranks. For the first three cases, gold /silver /bronze are handled separately. For the rest, just used a counter i.
            while(!q.isEmpty())
            {
                if(i==0)
                    map.put(q.poll(),"Gold Medal");
                else if(i==1)
                    map.put(q.poll(), "Silver Medal");
                else if(i==2)
                    map.put(q.poll(), "Bronze Medal");
                else
                    map.put(q.poll(), String.valueOf(i+1));
                i++;
            }
    // Map the relative ranks with the help of hash Map
            for (int j=0;j<nums.length;j++)
            {
                results[j]=map.get(nums[j]); 
            }
            return results ;
        }
    }
    

Log in to reply
 

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