Java Easy Solution O(nlogn) though


  • 0
        class Node implements Comparable<Node> {
            int val;
            int count;
            public Node(int val, int count) {
                this.val = val;
                this.count = count;
            }
            public int compareTo(Node other) {
                return other.count - this.count;
            }
        }
        
        public List<Integer> topKFrequent(int[] nums, int k) {
            List<Integer> res = new ArrayList<>();
            if (nums == null || nums.length == 0 || k <= 0) return res;
            Map<Integer, Node> map = new HashMap<>();
            for (int num : nums) {
                if (!map.containsKey(num)) map.put(num, new Node(num, 1));
                else map.get(num).count += 1;
            }
            List<Node> list = new ArrayList<Node>(map.values());
            Collections.sort(list);
            
            for (int i = 0; i < k; i++) {
                res.add(list.get(i).val);
            }
            return res;
        }
    

Log in to reply
 

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