Easy To understand HashMap solution in java using comparator


  • 0
    P
    class Solution {
        public List<Integer> topKFrequent(int[] nums, int k) {
            
            Map<Integer,Integer> unsorterMap = new HashMap<>();
            List<Integer> answer = new ArrayList<>();
                            
            for (int i=0;i<nums.length;i++){            
                if (unsorterMap.containsKey(nums[i])){
                    unsorterMap.put(nums[i],unsorterMap.get(nums[i])+1);    
                }else{
                    unsorterMap.put(nums[i],1);                   
                }                        
            }
            
            List<Map.Entry<Integer,Integer>> list = new ArrayList<>(unsorterMap.entrySet());
            
            Collections.sort(list, new Comparator<Map.Entry<Integer,Integer>>(){
                
                public int compare(Map.Entry<Integer,Integer> m1,Map.Entry<Integer,Integer> m2){
                    
                    return (m2.getValue()).compareTo(m1.getValue());
                }                        
            });
            
            Map<Integer,Integer> sortedMap = new LinkedHashMap<>();
            for (Map.Entry<Integer,Integer> m : list){
                sortedMap.put(m.getKey(),m.getValue());
                
            }
            
            for (Integer inte: sortedMap.keySet()){
                
                if (k==0){
                    break;
                }
                answer.add(inte);
                k--;
                
            }                
            
            return answer;
        }
    }
    

Log in to reply
 

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