前K个高频元素

描述:

给定一个非空的整数数组,返回其中出现频率前 k 高的元素。

示例 1:

输入: nums = [1,1,1,2,2,3], k = 2
输出: [1,2]
示例 2:

输入: nums = [1], k = 1
输出: [1]
说明:

你可以假设给定的 k 总是合理的,且 1 ≤ k ≤ 数组中不相同的元素的个数。
你的算法的时间复杂度必须优于 O(n log n) , n 是数组的大小。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/top-k-frequent-elements

思路分析:

1、前k个最大:建小根堆,每次弹出根上最小的元素
2、前k个最小:建大根堆,每次弹出根上最大的元素

如何构建小根堆:

【Java】 用PriorityQueue实现最大最小堆

PriorityQueue(优先队列),一个基于优先级堆的无界优先级队列。

实际上是一个堆(不指定Comparator时默认为最小堆),通过传入自定义的Comparator函数可以实现大顶堆。

    PriorityQueue<Integer> minHeap = new PriorityQueue<Integer>(); //小顶堆,默认容量为11
    PriorityQueue<Integer> maxHeap = new PriorityQueue<Integer>(11,new Comparator<Integer>(){ //大顶堆,容量11
        @Override
        public int compare(Integer i1,Integer i2){
            return i2-i1;
        }
    });

案例: 剑指offer(41) 最小的k个数

PriorityQueue的常用方法有:poll(),offer(Object),size(),peek()等。

插入方法(offer()、poll()、remove() 、add() 方法)时间复杂度为O(log(n)) ;
  remove(Object) 和 contains(Object) 时间复杂度为O(n);
  检索方法(peek、element 和 size)时间复杂度为常量。

代码实现:

注意:
一定要重写Comparator中的compare函数及其写法!!!
一定要重写Comparato中的comparer函数及其写法!!!
一定要重写Comparator中的compare函数及其写法!!!


class Solution {
    public List<Integer> topKFrequent(int[] nums, int k) {
        Map<Integer, Integer> map = new HashMap<>();
        // 使用字典,统计每个元素出现的次数,元素为键,元素出现的次数为值
        for (int i = 0; i < nums.length; i++) {
            if (map.containsKey(nums[i])) {
                map.put(nums[i], map.get(nums[i]) + 1);
            } else {
                map.put(nums[i], 1);
            }
        }
        // 遍历map,用最小堆保存频率最大的k个元素
        PriorityQueue<Integer> queue = new PriorityQueue<>(new Comparator<Integer>() {
            @Override
            public int compare(Integer a, Integer b) {
                return map.get(a) - map.get(b);
            }
        });
        for (Integer key : map.keySet()) {
            if (queue.size() < k) {
                queue.add(key);
            } else if (map.get(key) > map.get(queue.peek())){
                queue.remove();
                queue.add(key);
            }
        }
        List<Integer> ans = new ArrayList<>();
        // 取出最小堆中的元素
        while (!queue.isEmpty()) {
            ans.add(queue.remove());
        }
        return ans;
    }
}
### 找到数据集中K个高频元素的Python实现 以下是基于提供的引用内容和专业知识,针对寻找数据集中K个高频元素的一种高效解决方案。该方案利用了`collections.Counter`模块来统计频率,并通过小顶(heapq)筛选出K个高频元素。 #### 方法概述 为了满足时间复杂度的要求并减少不必要的计算开销,可以采用如下策略: - 使用 `collections.Counter` 统计输入列表中各元素的出现次数[^1]。 - 利用(Heap)这种数据结构维护当发现的K个高频元素。由于能够快速调整内部顺序,在处理大规模数据时效率较高[^2]。 下面是一个完整的 Python 实现: ```python from collections import Counter import heapq def topKFrequent(nums, k): # Step 1: Count the frequency of each element using Counter. count = Counter(nums) # Step 2: Use a heap to maintain the top-k frequent elements. return [item for item, freq in heapq.nlargest(k, count.items(), key=lambda x: x[1])] # Example usage: if __name__ == "__main__": nums = [1, 1, 1, 2, 2, 3] k = 2 result = topKFrequent(nums, k) print(result) # Output might be [1, 2], depending on implementation details. ``` 上述代码片段实现了以下逻辑: 1. **统计频率**:借助 `Counter` 类型创建字典形式的结果,其中键为原始数组中的数值,值为其对应的出现次数。 2. **构建**:调用内置函数 `heapq.nlargest()` 来获取按频率降序排列的最大k项[(key-value pairs)][]^2]^. 这种方法的时间复杂度主要由两部分组成: - 构建哈希表 O(n),n 是原数组长度; - 调整大小固定的最小至最终状态所需操作约为O(k log p),p表示不同数字总数[^4]. 综上所述,整体性能表现良好尤其当目标参数k远小于实际可能候选者数量级情况下更为明显优势突出。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值