Robust Java solution with Maps and Reverse sort


  • 0
    J

    Do find a very simple code with Maps and Reverse Sort

    '''

    class Solution {

    public List<Integer> topKFrequent(int[] nums, int k) {
        Map<Integer, Integer> counterMap = new HashMap<>();
        for (int x:nums)
        {
            int count = counterMap.getOrDefault(x, 0);
            counterMap.put(x, count+1);
        }        
        List<Map.Entry<Integer, Integer>> list = new LinkedList<>(counterMap.entrySet());
        Collections.sort(list, Collections.reverseOrder(new Comparator<Object>() {
            @SuppressWarnings("unchecked")
            public int compare(Object o1, Object o2) {
                return ((Comparable<Integer>) ((Map.Entry<Integer, Integer>) (o1)).getValue()).compareTo(((Map.Entry<Integer, Integer>) (o2)).getValue());
            }
        }));
    
        List<Integer> result = new ArrayList<Integer>();
        int i =0;
        for (Iterator<Map.Entry<Integer, Integer>> it = list.iterator(); it.hasNext();) {
            Map.Entry<Integer, Integer> entry = (Map.Entry<Integer, Integer>) it.next();
            result.add(entry.getKey());
            i++;
            if(i==k)
                    break;
        }
    
        return result;
        }
    

    }

    '''


Log in to reply
 

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