Using sortedSet() Java AC solution


  • 0
    public List<Integer> topKFrequent(int[] nums, int k) {
            SortedSet<Map.Entry<Integer, Integer>> sortedSet = new TreeSet<Map.Entry<Integer, Integer>>(
                new Comparator<Map.Entry<Integer, Integer>>() {
                    @Override 
                    public int compare(Map.Entry<Integer, Integer> e1, Map.Entry<Integer, Integer> e2) {
                        if (e2.getValue() != (e1.getValue())) 
                            return e2.getValue().compareTo(e1.getValue());
                        else return e2.getKey().compareTo(e1.getKey());
                    }
                });
            HashMap<Integer, Integer> map = new HashMap<>();
            List<Integer> res = new ArrayList<>();
            for (int n : nums) {
                map.put(n, map.getOrDefault(n, 0) + 1);
            }
            sortedSet.addAll(map.entrySet());
            Iterator<Map.Entry<Integer, Integer>> it = sortedSet.iterator();
            while (k > 0 && it.hasNext()) {
                k--;
                res.add(it.next().getKey());
            }
            return res;
        }
    

Log in to reply
 

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