347. Top K Frequent Elements

倒是不难,记记signature的事。属于打字练习。

public class Solution {
    class Node implements Comparable<Node>{
        int val;
        int freq;
        public Node(int val, int freq) {
            this.val = val;
            this.freq = freq;
        }
        public int compareTo(Node a) {
            return a.freq - this.freq;
        }
    }
    public List<Integer> topKFrequent(int[] nums, int k) {
        PriorityQueue<Node> pq = new PriorityQueue<Node>();
        HashMap<Integer, Node> map = new HashMap<>();
        List<Integer> result = new ArrayList<>();

        for (int i = 0; i < nums.length; ++i) {
            if (!map.containsKey(nums[i])) {
                Node node = new Node(nums[i], 1);
                map.put(nums[i], node);
            } else {
                Node node = map.get(nums[i]);
                node.freq++;
                map.put(nums[i], node);
            }
        }

        for (Integer key : map.keySet()) {
            pq.offer(map.get(key));
        }

        while (k > 0) {
            result.add(pq.poll().val);
            k--;
        }
        return result;
    }
}

results matching ""

    No results matching ""