[刷题]Top K Frequent Words

本文探讨了在给定字符串数组中找出出现频率最高的前K个单词的问题,并提供了两种不同的解决方案。第一种方法由于时间复杂度过高导致超时,第二种方法通过使用优先队列和自定义比较器实现了更高效的O(n log k)时间复杂度。

[LintCode]Top K Frequent Words

Version 1 失败

public class Solution {
    /**
     * @param words an array of string
     * @param k an integer
     * @return an array of string
     */
    public String[] topKFrequentWords(String[] words, int k) {
        // 2016-03-09  Time Limit Exceeded
        // 时间O(nk) 空间O(n)    
        // n是words数组长度
        if (words == null || words.length < 1 || k <= 0) {
            return new String[0];
        }
        HashMap<String, Integer> map = new HashMap<>();
        // 遍历words,计算每一个词出现的次数
        for (String word : words) {
            if (word == null) {
                continue;
            }
            if (!map.containsKey(word)) {
                map.put(word, 1);
            } else {
                map.put(word, map.get(word) + 1);
            }
        }
        
        // 下面代码的时间效率太低 O(nk)
        String[] rst = new String[k];
        int max = 0;
        for (int i = 0; i < k; i++) {
            for (String each : map.keySet()) {
                if (map.get(each) > max) {
                    max = map.get(each);
                    rst[i] = each;
                }
                if (map.get(each) == max && leftIsSmaller(each, rst[i])) {
                    rst[i] = each;
                }
            }
            map.remove(rst[i]);
            max = 0;
        }
        return rst;
    }
    
    /**
     * 比较两个字符串的大小
     */
    private boolean leftIsSmaller(String left, String right) {
        int length = Math.min(left.length(), right.length());
        for (int i = 0; i < length; i++) {
            if (left.charAt(i) > right.charAt(i)) {
                return false;
            } 
            if (left.charAt(i) < right.charAt(i)) {
                return true;
            }
        }
        if (left.length() < right.length()) {
            return true;
        } else {
            return false;
        }
    }
}

Version 2

class Pair {
    public String name;
    public int value;
    
    public Pair(String name, int value) {
        this.name = name;
        this.value = value;
    }
}

public class Solution {
    /**
     * @param words an array of string
     * @param k an integer
     * @return an array of string
     */
    
    // 定义比较器 
    Comparator<Pair> comparator = new Comparator<Pair>() {
        public int compare(Pair left, Pair right) {
            if (left.value != right.value) {
                return left.value - right.value;
            } else {
                // return left.name.compareTo(right.name);
                return right.name.compareTo(left.name);
            }
        }
    };
    
    public String[] topKFrequentWords(String[] words, int k) {
        // 2016-3-14 O(nlogk) time and O(n) space
        if (words == null || words.length == 0 || k <= 0) {
            return new String[0];
        }
        if (words.length < k) {
            return null;
        }
        
        // O(n) time
        HashMap<String, Integer> map = new HashMap<>();
        for (String word : words) {
            if (!map.containsKey(word)) {
                map.put(word, 1);
            } else {
                map.put(word, map.get(word) + 1);
            }
        }
        
        // 队列的容量是k    O(nlogk) time
        PriorityQueue<Pair> queue = new PriorityQueue<Pair>(k, comparator);
        for (String key : map.keySet()) {
            Pair newPair = new Pair(key, map.get(key));
            if (queue.size() < k) {
                queue.add(new Pair(key, map.get(key)));
            } else if (comparator.compare(queue.peek(), newPair) < 0) {
                queue.poll();
                queue.add(new Pair(key, map.get(key)));
            }
        }
        
        // O(klogk) time
        String[] rst = new String[k];
        for (int i = k - 1; i >= 0; i--) {
            rst[i] = queue.poll().name;
        }
        return rst;
    }
}


<think> 我们被要求解决Top K Frequent Elements问,即给定一个整数数组nums和整数k,返回出现频率前k高的元素。 根据站内引用,有几种方法: 1. 使用哈希表统计频率,然后使用优先队列(堆)来获取前k个元素(引用[2]和引用[3]) 2. 使用桶排序的思想(引用[4]) 我将介绍这两种方法,并给出代码示例(以C++、Java和Python为例)。 方法一:最小堆(优先队列) 思路: - 先用哈希表统计每个数字出现的频率。 - 然后使用一个最小堆(按频率排序),堆的大小保持为k。遍历哈希表的每个元素,将元素加入堆中,如果堆的大小超过k,则弹出堆顶(频率最小的元素)。这样,堆中剩下的就是频率最大的k个元素。 - 注意:最小堆通常比较的是元素的频率。在C++中,priority_queue默认是大顶堆,所以我们可以通过自定义比较函数来构建最小堆。或者我们也可以使用大顶堆,但需要将全部元素放入堆中,然后取前k个,这样效率较低(O(nlogk) vs O(nlogn))。因此,我们采用最小堆,保持堆的大小为k,这样效率更高。 方法二:桶排序 思路: - 先用哈希表统计每个数字出现的频率。 - 然后创建一个数组(桶),数组的下标表示频率,数组的元素是一个列表,存储该频率下的所有数字。 - 由于同一个频率可能有多个数字,所以我们需要一个列表数组。 - 然后从高频率到低频率遍历桶,取出k个数字即可。 下面分别实现这两种方法。 方法一(最小堆)的步骤: 1. 遍历数组,用哈希表记录每个数字出现的频率。 2. 初始化一个最小堆(优先队列),堆中元素为(频率,数字)。注意:最小堆根据频率比较,所以我们可以将频率作为键,但是注意最小堆的堆顶是最小元素,而我们想要保留的是频率大的,所以当堆的大小超过k时,我们就弹出堆顶(当前最小的频率),这样最后剩下的就是最大的k个。 3. 遍历哈希表,将每个数字和其频率组成对加入堆中,同时控制堆的大小不超过k。 4. 最后,将堆中的元素取出(注意:堆中元素是频率从大到小?实际上,最小堆的堆顶是最小的,所以最后堆中保存的是最大的k个,但是堆顶是最小的那个,所以取出来的时候顺序无所谓,我们只要数字即可)。 方法二(桶排序)的步骤: 1. 遍历数组,用哈希表记录每个数字出现的频率。 2. 创建桶数组,桶数组的长度为数组长度+1(因为频率最大为数组长度)。 3. 遍历哈希表,将数字放入对应的频率桶中。 4. 从桶数组的最后一个(即最高频率)开始向前遍历,将桶中的数字加入结果列表,直到结果列表中有k个元素。 下面用代码展示: 注意:由于站内引用提供了C++的代码(引用[2]使用了大顶堆,但效率不高),我们将按照更高效的最小堆方法实现。桶排序的方法在引用[4]中也有。 我们以三种语言实现最小堆方法,两种语言实现桶排序方法(因为桶排序方法在引用[4]中是Java,我们将用Python实现桶排序)。 首先,方法一(最小堆)的代码: C++版本(使用STL的priority_queue,注意构建最小堆): ```cpp #include <vector> #include <queue> #include <unordered_map> using namespace std; class Solution { public: vector<int> topKFrequent(vector<int>& nums, int k) { unordered_map<int, int> freq; for (int num : nums) { freq[num]++; } // 构建最小堆,使用pair,第一个元素是频率,第二个元素是数字 // 自定义比较函数,注意priority_queue默认是大顶堆,所以我们需要使用greater并配合pair auto cmp = [](pair<int, int>& a, pair<int, int>& b) { return a.first > b.first; // 最小堆,比较频率 }; priority_queue<pair<int, int>, vector<pair<int, int>>, decltype(cmp)> pq(cmp); for (auto& [num, count] : freq) { pq.push({count, num}); if (pq.size() > k) { pq.pop(); // 弹出最小的那个 } } vector<int> res; while (!pq.empty()) { res.push_back(pq.top().second); pq.pop(); } // 注意:这样取出的顺序是从小到大(因为堆顶是最小的频率,我们每次弹出的是最小的,最后剩下的在堆底是较大的,但弹出时先弹堆顶,所以res中顺序是频率由小到大,不过目不要求顺序,但有时要求从大到小,我们可以反转一下,但目不要求顺序,所以可以不反转) // 但是目要求顺序任意,所以直接返回即可。 return res; } }; ``` Java版本(使用PriorityQueue,注意Java的PriorityQueue默认是最小堆,但我们需要最小堆,所以使用最小堆,但注意比较器的写法): ```java class Solution { public int[] topKFrequent(int[] nums, int k) { Map<Integer, Integer> frequencyMap = new HashMap<>(); for (int num : nums) { frequencyMap.put(num, frequencyMap.getOrDefault(num, 0) + 1); } // 创建最小堆,按照频率升序(堆顶是频率最小的) PriorityQueue<Map.Entry<Integer, Integer>> pq = new PriorityQueue<>((a, b) -> a.getValue() - b.getValue()); for (Map.Entry<Integer, Integer> entry : frequencyMap.entrySet()) { pq.offer(entry); if (pq.size() > k) { pq.poll(); // 弹出堆顶(当前最小的) } } int[] res = new int[k]; int idx = 0; while (!pq.isEmpty()) { res[idx++] = pq.poll().getKey(); } return res; } } ``` Python版本(使用heapq,注意heapq是最小堆): ```python import heapq from collections import defaultdict class Solution: def topKFrequent(self, nums: List[int], k: int) -> List[int]: freq = defaultdict(int) for num in nums: freq[num] += 1 # 使用最小堆,我们存储的是(频率,数字),注意堆的大小为k heap = [] for num, count in freq.items(): heapq.heappush(heap, (count, num)) if len(heap) > k: heapq.heappop(heap) # 此时堆中就是最大的k个,但是每个元素是(count, num),我们只需要num return [item[1] for item in heap] ``` 注意:在Python中,heapq是最小堆,所以堆顶是最小的频率。我们每次push后,如果堆的大小超过k,就pop掉最小的那个,这样最后剩下的就是最大的k个。 方法二:桶排序(以Python实现,因为引用[4]中提供了Java版本,这里我们用Python) 步骤: 1. 统计频率。 2. 创建桶,桶的索引表示频率,桶中存储该频率下的所有数字。 3. 从高频率到低频率遍历桶,直到收集到k个元素。 Python版本: ```python from collections import defaultdict class Solution: def topKFrequent(self, nums: List[int], k: int) -> List[int]: freq = defaultdict(int) max_freq = 0 for num in nums: freq[num] += 1 if freq[num] > max_freq: max_freq = freq[num] # 创建桶,索引0不使用,从1到max_freq buckets = [[] for _ in range(max_freq+1)] for num, count in freq.items(): buckets[count].append(num) res = [] # 从最高频率开始向下遍历 for i in range(max_freq, 0, -1): if buckets[i]: for num in buckets[i]: res.append(num) if len(res) == k: return res return res ``` 注意:桶排序的方法时间复杂度为O(n),但是当频率分布不均匀(比如很多不同的频率)并且n很大时,桶的空间可能比较大,但实际效率还是很高。 两种方法比较: - 最小堆方法:时间复杂度O(nlogk),空间复杂度O(n)(哈希表和堆) - 桶排序方法:时间复杂度O(n),空间复杂度O(n)(哈希表和桶) 因此,桶排序方法在时间复杂度上更优,但空间复杂度可能较高(如果频率分布很分散,但实际频率最大为n,所以需要长度为n+1的桶,而每个桶里存数字,总数字个数为不同数字的个数,所以空间是O(n))。 根据实际情况选择方法。 下面生成相关问: </think> ### 解决 Top K Frequent Elements 问的算法 #### 方法一:最小堆(优先队列)法 **时间复杂度**:$O(n \log k)$,空间复杂度:$O(n)$ **步骤**: 1. **统计频率**:使用哈希表记录每个元素出现次数 2. **维护最小堆**:保持堆大小为 $k$,堆顶是当前最小频率元素 3. **提取结果**:堆中剩余元素即为 Top K 高频元素 ```python import heapq from collections import Counter def topKFrequent(nums, k): freq = Counter(nums) heap = [] for num, count in freq.items(): heapq.heappush(heap, (count, num)) if len(heap) > k: heapq.heappop(heap) # 移除最小元素 return [num for _, num in heap] # 示例 print(topKFrequent([1,1,1,2,2,3], 2)) # 输出: [1,2] ``` #### 方法二:桶排序法 **时间复杂度**:$O(n)$,空间复杂度:$O(n)$ **步骤**: 1. **统计频率**:使用哈希表记录频率 2. **创建频率桶**:索引表示频率,值存储对应元素 3. **反向遍历桶**:从高频率向低频率提取元素 ```python from collections import defaultdict def topKFrequent(nums, k): freq = defaultdict(int) max_freq = 0 for num in nums: freq[num] += 1 max_freq = max(max_freq, freq[num]) buckets = [[] for _ in range(max_freq+1)] for num, count in freq.items(): buckets[count].append(num) res = [] for i in range(max_freq, 0, -1): if buckets[i]: res.extend(buckets[i]) if len(res) >= k: return res[:k] return res ``` #### 方法三:快速选择法(Hoare's 选择) **时间复杂度**:平均 $O(n)$,最坏 $O(n^2)$,空间复杂度:$O(n)$ ```python import random from collections import Counter def topKFrequent(nums, k): freq = Counter(nums) unique = list(freq.keys()) def partition(left, right): pivot_idx = random.randint(left, right) pivot_freq = freq[unique[pivot_idx]] unique[pivot_idx], unique[right] = unique[right], unique[pivot_idx] i = left for j in range(left, right): if freq[unique[j]] > pivot_freq: # 按频率降序排列 unique[i], unique[j] = unique[j], unique[i] i += 1 unique[i], unique[right] = unique[right], unique[i] return i def quickselect(left, right): if left == right: return pos = partition(left, right) if pos == k-1: return elif pos < k-1: quickselect(pos+1, right) else: quickselect(left, pos-1) quickselect(0, len(unique)-1) return unique[:k] ``` ### 算法对比 | 方法 | 时间复杂度 | 空间复杂度 | 适用场景 | |--------------|------------------|------------|------------------------------| | **最小堆** | $O(n \log k)$ | $O(n)$ | $k$ 远小于 $n$ 时最优 | | **桶排序** | $O(n)$ | $O(n)$ | 频率分布均匀时最优 | | **快速选择** | $O(n)$ (平均) | $O(n)$ | 需要部分排序时最优 | ### 关键点说明 1. **最小堆方法**中,堆大小保持为 $k$ 确保时间复杂度优化为 $O(n \log k)$ 而非 $O(n \log n)$[^2][^3] 2. **桶排序**利用数组索引直接对应频率,反向遍历实现 $O(n)$ 时间复杂度[^4] 3. **快速选择**本质是快速排序的变种,在平均情况下可达到线性时间复杂度[^1]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值