代码随想录算法训练营第13天 | 栈与队列part03:● 239. 滑动窗口最大值● 347.前 K 个高频元素● 总结

文章介绍了两种算法问题的解决方案:一是使用优先队列(maxheap)求解滑动窗口内的最大值,关键在于更新窗口时的pop操作;二是利用排序和哈希表找到数组中的前K个高频元素,维护一个最大堆来跟踪高频元素。
摘要由CSDN通过智能技术生成

#239 滑动窗口最大值是hard!!!好难的,是我做的第一个hard吧

但这是补的博客,没有仔细分析。复习的时候再仔细总结。

vector<int> maxSlidingWindow(vector<int>& nums, int k) {
        //方法一 use priority_queue (max heap)
        vector<int> result;
        priority_queue<pair<int, int>> maxHeap; 
        
        for (int i = 0; i < nums.size(); i++) {
        
            while (!maxHeap.empty() && maxHeap.top().second <= i - k) {
                maxHeap.pop();
            }
            //maxHeap.top().second <= i - k 这里很关键
            //第一个窗口结束时,虽然top first确实是最大值3,但是 second是 indx还是0,我们还是会把1弹出
            
            maxHeap.push({nums[i], i});
            
            if (i >= k - 1) {
                result.push_back(maxHeap.top().first);
            }
        }
        
        return result;
    }

#347 前 K 个高频元素 Medium

这是补的博客,没有仔细分析。复习的时候再仔细总结。

vector<int> topKFrequent(vector<int>& nums, int k) {
        priority_queue<pair<int,int>> maxheap;//cnt,value
        sort(nums.begin(),nums.end());
        int value=nums[0];
        
        int cnt=0;
        for(int i=0;i<nums.size();i++){
            
            if(value==nums[i]){
                cnt++;
            }
            else{
                maxheap.push(make_pair(cnt,value));
                cnt=1;
                value=nums[i];
            }
            
        }
        maxheap.push(make_pair(cnt,value));

        //check
        /*
        priority_queue<pair<int,int>> tempheap = maxheap;
        while (!tempheap.empty()) {
            pair<int, int> ele = tempheap.top();
            cout << "cnt: " << ele.first << ", value: " << ele.second << endl;
            tempheap.pop();
        }
        */
        vector<int> res;
        while(!maxheap.empty() && (k--)){
            res.push_back(maxheap.top().second);
            maxheap.pop();
        }
        return res;

        
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值