[LeetCode 347] Top K Frequent Elements (Medium)

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

Example 1:

Input: nums = [1,1,1,2,2,3], k = 2
Output: [1,2]

Example 2:

Input: nums = [1], k = 1
Output: [1]

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.

Solution

  1. Top k最大值问题,用min-heap (因为是与最小值比较,所以用最小堆)
  2. 题目要求找的是 k most frequent elements, 所以需要记录 element 以及其frequency ==> HashMap
  3. 再对HashMap中每个Entrymin-heap(priorityQueue),根据frequency排序,找到Top K Entry
    • 需要自定义Comparator,根据Entry中的frequency排序
  4. Top K EntryKey collection就是 Top K Frequent Elements
class Solution {
    public List topKFrequent(int[] nums, int k) {
        Map numberToFrequency = new HashMap<> ();
        
        // 1. Get number and its frequency
        for (int num : nums) {
            numberToFrequency.put (num, numberToFrequency.getOrDefault (num, 0) + 1);
        }
        
        // 2. Use priority Queue to get the top K frequenct elements
        PriorityQueue > minHeap = new PriorityQueue<> (
            (obj1, obj2) -> obj1.getValue () - obj2.getValue ()
        );
        
        for (Map.Entry pair : numberToFrequency.entrySet()) {
            if (minHeap.size () < k) {
                minHeap.offer (pair);
                continue;
            }
            
            if (pair.getValue () > minHeap.peek ().getValue ()) {
                minHeap.poll ();
                minHeap.offer (pair);
            }
        }
        
        // 3. Get the key sets from the minHeap
        List result = new ArrayList<> ();
        
        Iterator> it = minHeap.iterator ();
        while (it.hasNext ()) {
            result.add (it.next ().getKey());
        }
        
        return result;
    }
}

你可能感兴趣的:([LeetCode 347] Top K Frequent Elements (Medium))