• 剑指 Offer 59


    一、题目描述

    给定一个数组 nums 和滑动窗口的大小 k,请找出所有滑动窗口里的最大值。

    示例:

    输入: nums = [1,3,-1,-3,5,3,6,7], 和 k = 3
    输出: [3,3,5,5,6,7]
    解释:

    滑动窗口的位置 最大值
    --------------- -----
    [1 3 -1] -3 5 3 6 7 3
    1 [3 -1 -3] 5 3 6 7 3
    1 3 [-1 -3 5] 3 6 7 5
    1 3 -1 [-3 5 3] 6 7 5
    1 3 -1 -3 [5 3 6] 7 6
    1 3 -1 -3 5 [3 6 7] 7

    提示:

    你可以假设 k 总是有效的,在输入数组不为空的情况下,1 ≤ k ≤ 输入数组的大小。

    二、题解

    方法一:使用优先级队列

    要注意的是,要将数据对应的下标,与数据作为一个元组传入优先级队列中

    class Solution {
    public:
        vector<int> maxSlidingWindow(vector<int>& nums, int k) {
            int n = nums.size();
            vector<int> res;
            if(n==0) return res;
            priority_queue<pair<int,int> > pq;
            for(int i=0;i<k;i++){
                pq.push(make_pair(nums[i],i));
            }
            res.emplace_back(pq.top().first);
            for(int start = 1,end = k;end<nums.size();start++,end++){
                pq.push(make_pair(nums[end],end));
                while(pq.top().second < start)
                    pq.pop();
                res.emplace_back(pq.top().first);
            }
            return res;
        }
    };

     方法二:使用双端单调队列

    保持一个单调递减的双端队列,且保证队列中的元素全为当前窗口的元素

    class Solution {
        public int[] maxSlidingWindow(int[] nums, int k) {
            int n = nums.length;
            if(n==0) return new int[]{};
            int[] res = new int[n - k + 1];
            Deque<Integer> pq = new LinkedList<>();
            for(int i=0;i<k;i++){
                while(!pq.isEmpty()&&pq.peekLast()<nums[i]){
                    pq.pollLast();
                }
                pq.addLast(nums[i]);
            }
            res[0] = pq.peekFirst();
            for(int left = 1,right = k;right<n;left++,right++){
                if(pq.peekFirst()==nums[left-1]){
                    pq.pollFirst();
                }
                while(!pq.isEmpty()&&pq.peekLast()<nums[right]){
                    pq.pollLast();
                }
                pq.addLast(nums[right]);
                res[left] = pq.peekFirst();
            }
            return res;
        }
    }

  • 相关阅读:
    load data to matlab
    Apriori algorithm
    LOGIN Dialogue of Qt
    Methods for outlier detection
    MFC改变对话框背景色
    g++宏扩展
    Some key terms of Data Mining
    Qt QLabel 显示中文
    How To Debug a Pyhon Program
    C++命名规范
  • 原文地址:https://www.cnblogs.com/ttzz/p/14405552.html
Copyright © 2020-2023  润新知