Java Simple Solution


  • 0
    F
        public List<Integer> topKFrequent(int[] nums, int k) {
            Map<Integer,Integer> map=new HashMap<>();
            for(int num:nums){
                map.put(num,map.getOrDefault(num,0)+1);
            }
            ArrayList<Map.Entry<Integer,Integer>> list=new ArrayList<>(map.entrySet());
            Collections.sort(list,new Comparator<Map.Entry<Integer,Integer>>(){
                public int compare(Map.Entry<Integer,Integer> o1,Map.Entry<Integer,Integer> o2){
                    return (o2.getValue()).compareTo(o1.getValue());
                }
            });
            ArrayList<Integer> res=new ArrayList<>();
            for(int i=0;i<k;i++){
                res.add(list.get(i).getKey());
            }
            return res.subList(0, k);
        }
    }```

Log in to reply
 

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