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 統(tǒng)計(jì)詞頻;
  • 再維護(hù)一個(gè)容量為 k 的最小堆,里面存的結(jié)構(gòu)是頻率和數(shù)字的鍵值對(duì),最小堆中的元素個(gè)數(shù)還沒到 k 就繼續(xù)往里面扔元素;到了就看要新添的元素能不能把堆頂?shù)脑財(cái)D掉,使堆維護(hù)的 k 個(gè)元素都是目前頻率最高的 k 個(gè)元素;

解法實(shí)現(xiàn)(一)

時(shí)間復(fù)雜度
  • O(NlogK);
空間復(fù)雜度
  • O(N + K);
關(guān)鍵字

優(yōu)先隊(duì)列 最小堆 詞頻統(tǒng)計(jì) HashMap

實(shí)現(xiàn)細(xì)節(jié)
  • PriorityQueue 在實(shí)例化的時(shí)候,要傳入一個(gè)比較器 new PairComparator(),比較器 PairComparator 的實(shí)現(xiàn)不用太較真,關(guān)于正負(fù),一次沒寫對(duì),換一下就行了;
package leetcode._347;

import javafx.util.Pair;

import java.util.*;

public class Solution347_1 {

    private class PairComparator implements Comparator<Pair<Integer, Integer>> {

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

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

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

        HashMap<Integer, Integer> freq = new HashMap<Integer, Integer>();
        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<Pair<Integer, Integer>> pq = new PriorityQueue<Pair<Integer, Integer>>(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<Integer> res = new ArrayList<Integer>();
        while(!pq.isEmpty())
            res.add(pq.poll().getValue());

        return res;
    }

}

返回 LeetCode [Java] 目錄

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容