【重点】【堆】347.前K个高频元素

题目

法1:小根堆

Python

在Python的heapq模块中,当堆元素是数组(或列表)时,默认的比较规则是逐元素比较,直到找到第一个不同的元素。具体规则如下:

按元素顺序逐个比较:
比较数组的第一个元素,若不同则直接决定大小关系
若第一个元素相同,则比较第二个元素,依此类推
若所有元素都相同,则认为两个数组相等

# 写法1:
class Solution:
    def topKFrequent(self, nums: List[int], k: int) -> List[int]:
        tmpMap = collections.Counter(nums)
        minHeap = []
        for key, val in tmpMap.items():
            if len(minHeap) < k:
                heapq.heappush(minHeap, [val, key])
            else:
                heapq.heappushpop(minHeap, [val, key])
        
        return [item[1] for item in minHeap]

# 写法2: 
class Solution:
    def topKFrequent(self, nums: List[int], k: int) -> List[int]:
        tmp_map = collections.Counter(nums)
        min_heap = []
        for key, val in tmp_map.items():
            if len(min_heap) < k:
                heapq.heappush(min_heap, (val, key))
            else:
                heapq.heappushpop(min_heap, (val, key))
        
        return [item[1] for item in min_heap]

Java

class Solution {
    public int[] topKFrequent(int[] nums, int k) {
        Map<Integer, Integer> valToCountMap = new HashMap<>();
        for (int i : nums) {
            valToCountMap.put(i, valToCountMap.getOrDefault(i, 0) + 1);
        }
        PriorityQueue<int[]> queue = new PriorityQueue<>((a, b) -> a[1] - b[1]);
        for (Map.Entry<Integer, Integer> entry : valToCountMap.entrySet()) {
            int val = entry.getKey(), count = entry.getValue();
            if (queue.size() == k) {
                if (count > queue.peek()[1]) {
                    queue.poll();
                    queue.offer(new int[]{val, count});
                }
            } else {
                queue.offer(new int[]{val, count});
            }
        }

        int[] res = new int[k];
        for (int i = 0; i < k; ++i) {
            res[i] = queue.poll()[0];
        }

        return res;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值