一、题目描述

给定一个数组 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;
    }
}

 

posted on 2021-02-15 22:00  曹婷婷  阅读(37)  评论(0编辑  收藏  举报