Relative Ranks, HashMap and PriorityQueue


  • 0

    Use HashMap to record index, use priority queue to find the order.

    public class Solution {
        public String[] findRelativeRanks(int[] nums) {
            String[] res = new String[nums.length]; 
            PriorityQueue<Integer> pq = new PriorityQueue<>(nums.length,
                new Comparator<Integer>(){
                public int compare(Integer a, Integer b){
                    return b-a;
                }
            });
            Map<Integer, Integer> hmap = new HashMap<>();
            for(int i = 0 ; i < nums.length ; i++){
                hmap.put(nums[i],i);
                pq.add(nums[i]);
            }
            int j = 1;
            while(!pq.isEmpty()){
                int cur = pq.poll();
                if(j == 1){
                    res[hmap.get(cur)] = "Gold Medal"; j++;
                }
                else if(j == 2){
                    res[hmap.get(cur)] = "Silver Medal"; j++;
                }
                else if(j == 3){
                    res[hmap.get(cur)] = "Bronze Medal"; j++;
                }
                else{
                    res[hmap.get(cur)] = ""+ j ; j++;
                }
            }
            return res;
        }
    }
    

Log in to reply
 

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