HashMap Sort by Value Using Java


  • 0
    W
    class Solution {
        public List<Integer> topKFrequent(int[] nums, int k) {
            List<Integer> rtn = new LinkedList<Integer>();
            Map<Integer, Integer> counts= new HashMap<Integer,Integer>();
            int count=0;
            for (int tmp: nums){
               count= counts.getOrDefault(tmp,0);
               counts.put(tmp,count+1); 
            }
            counts= sortByValue(counts);
            int i=0;
            for (Map.Entry<Integer,Integer> entry:counts.entrySet()){
                
                if(i<k){
                    rtn.add(entry.getKey());
                }
                i++;
            }
            
            return rtn;
        }
       public static <K, V extends Comparable<? super V>> Map<K, V> 
        sortByValue(Map<K, V> map) {
        List<Map.Entry<K, V>> list = new LinkedList<>(map.entrySet());
        Collections.sort( list, new Comparator<Map.Entry<K, V>>() {
            public int compare(Map.Entry<K, V> o1, Map.Entry<K, V> o2) {
                return (o2.getValue()).compareTo(o1.getValue());
            }
        });
    
        Map<K, V> result = new LinkedHashMap<>();
        for (Map.Entry<K, V> entry : list) {
            result.put(entry.getKey(), entry.getValue());
        }
        return result;
        }
    }
    

Log in to reply
 

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