LeetCode 347 Top K Frequent Elements

题目

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.

解法思路(一)

  • 先用 HashMap 统计词频;
  • 再维护一个容量为 k 的最小堆,里面存的结构是频率和数字的键值对,最小堆中的元素个数还没到 k 就继续往里面扔元素;到了就看要新添的元素能不能把堆顶的元素挤掉,使堆维护的 k 个元素都是目前频率最高的 k 个元素;

解法实现(一)

时间复杂度
  • O(NlogK);
空间复杂度
  • O(N + K);
关键字

优先队列 最小堆 词频统计 HashMap

实现细节
  • PriorityQueue 在实例化的时候,要传入一个比较器 new PairComparator(),比较器 PairComparator 的实现不用太较真,关于正负,一次没写对,换一下就行了;
package leetcode._347;

import javafx.util.Pair;

import java.util.*;

public class Solution347_1 {

    private class PairComparator implements Comparator> {

        @Override
        public int compare(Pair p1, Pair p2){
            if(p1.getKey() != p2.getKey())
                return p1.getKey() - p2.getKey();
            return p1.getValue() - p2.getValue();
        }
    }

    public List topKFrequent(int[] nums, int k) {

        if(k <= 0)
            throw new IllegalArgumentException("k should be greater than 0");

        HashMap freq = new HashMap();
        for(int i = 0 ; i < nums.length ; i ++)
            if(freq.containsKey(nums[i]))
                freq.put(nums[i], freq.get(nums[i]) + 1);
            else
                freq.put(nums[i], 1);

        if(k > freq.size())
            throw new IllegalArgumentException("k should be less than the number of unique numbers in nums");

        PriorityQueue> pq = new PriorityQueue>(new PairComparator());
        for(Integer num: freq.keySet()){
            int numFreq = freq.get(num);
            if(pq.size() == k){
                if(numFreq > pq.peek().getKey()){
                    pq.poll();
                    pq.add(new Pair(numFreq, num));
                }
            }
            else
                pq.add(new Pair(numFreq, num));
        }

        ArrayList res = new ArrayList();
        while(!pq.isEmpty())
            res.add(pq.poll().getValue());

        return res;
    }

}

返回 LeetCode [Java] 目录

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