跳转至

239.Sliding Window Maximum

Tags: Hard Heap Sliding Window

Links: https://leetcode.com/problems/sliding-window-maximum/


Given an array nums, there is a sliding window of size k which is moving from the very left of the array to the very right. You can only see the k numbers in the window. Each time the sliding window moves right by one position. Return the max sliding window.

Example:

Input: nums = [1,3,-1,-3,5,3,6,7], and k = 3
Output: [3,3,5,5,6,7] 
Explanation: 

Window position                Max
---------------               -----
[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

Note: You may assume k is always valid, 1 ≤ k ≤ input array's size for non-empty array.

Follow up: Could you solve it in linear time?


解法一:ST表的RMQ

class Solution {
    int d[100005][21];
    int n;
public:
    vector<int> maxSlidingWindow(vector<int>& nums, int k) {
        std::ios_base::sync_with_stdio(false);
        cin.tie(NULL);
        cout.tie(NULL);

        if (nums.size() == 0) return {};

        n = nums.size();
        vector<int> res(n - k + 1);

        init(nums);
        for (int i = 0; i + k - 1 < n; ++i) {
            res[i] = RMQ(i + 1, i + k);
        }
        return res;
    }

    void init(const vector<int> & nums)
    {
        for (int i = 1; i <= n; ++i) d[i][0] = nums[i - 1];
        for (int j = 1; (1 << j) <= n; ++j) {
            for (int i = 1; i + (1 << j) - 1 <= n; ++i) {
                d[i][j] = max(d[i][j - 1], d[i + (1 << (j - 1))][j - 1]);
            }
        }
    }

    int RMQ(int L, int R)
    {
        int k = log2(R - L + 1);

        return max(d[L][k], d[R - (1 << k) + 1][k]);
    }
};

很典型的RMQ问题,采用ST表,已经在《数据结构——ST表》总结过了,建表的时间复杂度为O(n \log n),查询操作为O(1)

如果要求线性时间复杂度,其实就是利用线段树来进行建表操作,建表时间复杂度为O(n),查询为\log n,时间复杂度仍然是O(n \log n)

解法二:单调队列

其实很明显这个就是**单调队列**的模板题目。在《挑战程序设计竞赛》的4.4.2节

class Solution {
public:
    vector<int> maxSlidingWindow(vector<int>& nums, int k) {
        std::ios_base::sync_with_stdio(false);
        cin.tie(NULL);
        cout.tie(NULL);

        vector<int> res;
        deque<int> q;
        for (int i = 0; i < nums.size(); ++i) {
            if (!q.empty() && q.front() == i - k) q.pop_front();
            while (!q.empty() && nums[q.back()] < nums[i]) q.pop_back();
            q.push_back(i);
            if (i >= k - 1) res.push_back(nums[q.front()]);
        }
        return res;
    }
};
Runtime: 44 ms, faster than 99.94% of C++ online submissions for Sliding Window Maximum.
Memory Usage: 12.3 MB, less than 100.00% of C++ online submissions for Sliding Window Maximum.

解法三:区间树

《算法问题实战策略》17.4其他学习内容,区间树可以快速求解区间乘积、区间最小/最大值、最大出现频率等(莫队算法也可以解决出现频率问题)

解法四:线段树