LeetCode Top K Frequent Elements

Posted Dylan_Java_NYC

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode Top K Frequent Elements相关的知识,希望对你有一定的参考价值。

原题链接在这里:https://leetcode.com/problems/top-k-frequent-elements/

题目:

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

For example,
Given [1,1,1,2,2,3] and k = 2, return [1,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.

题解:

先计算出element 和对应的frequency.

然后使用bucket sort. 把element按照出现频率放在bucket中.

因为一共只有n 个元素, 那么最大的频率只能是n. n = nums.length. 所以bucket的大小是n+1, 才能对应最大频率.

然后从bucket后扫到前,因为后面的elements 频率高. 加到res中直到res的size到达k.

Note: bucket的生成等号右边是ArrayList[] 而不能是ArrayList<Integer>[], 因为complier 不能判准加进ArrayList中的type, 只有run time才能知道. 所以这里complier不允许确定type.

Time Complexity: O(n), n = nums.length.

Space: O(n).

AC Java:

 1 class Solution {
 2     public List<Integer> topKFrequent(int[] nums, int k) {
 3         List<Integer> res = new ArrayList<Integer>();
 4         if(nums == null || nums.length == 0){
 5             return res;
 6         }
 7         
 8         HashMap<Integer, Integer> hm = new HashMap<Integer, Integer>();
 9         for(int num : nums){
10             hm.put(num, hm.getOrDefault(num, 0)+1);
11         }
12         
13         ArrayList [] buckets= new ArrayList[nums.length+1];
14         for(Map.Entry<Integer, Integer> entry : hm.entrySet()){
15             int freq = entry.getValue();
16             if(buckets[freq] == null){
17                 buckets[freq] = new ArrayList<Integer>();
18             }
19             buckets[freq].add(entry.getKey());
20         }
21         
22         for(int i = buckets.length-1; i>=0 && res.size()<k; i--){
23             if(buckets[i] != null){
24                 res.addAll(buckets[i]);
25             }
26         }
27         
28         return res;
29     }
30 }

类似Sort Characters By FrequencyTop K Frequent WordsK Closest Points to Origin.

以上是关于LeetCode Top K Frequent Elements的主要内容,如果未能解决你的问题,请参考以下文章

#Leetcode# 347. Top K Frequent Elements

LeetCode 347. Top K Frequent Elements

[leetcode]347. Top K Frequent Elements

***Leetcode 692. Top K Frequent Words

Leetcode 692: Top K Frequent Words

LeetCode 347. Top K Frequent Elements