Top K Frequent Elements

PriorityQueue<Map.Entry<Integer, Integer>> heap = new PriorityQueue<>((a,b) -> (a.getValue() - b.getValue()));

Given a non-empty array of integers, return the k most frequent elements.

Example 1:

Example 2:

Note:

  • You may assume k is always valid, 1 ≤ k ≤ number of unique elements.

  • Your algorithm's time complexity must be better than O(n log n), where n is the array's size.

n+n*logk

priority queue based on heap, o(logn) most time, here totally time o(n)

二刷

三刷

Last updated