GH1995 / leetcode-test-and-run

方便 leetcode 刷题的小工具
GNU General Public License v2.0
0 stars 0 forks source link

239. 239. Sliding Window Maximum 滑动窗口最大值 #45

Open GH1995 opened 5 years ago

GH1995 commented 5 years ago

239. Sliding Window Maximum

Difficulty: Hard

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?

Solution

Language: C++

class Solution {
public:
    vector<int> maxSlidingWindow(vector<int> &nums, int k) {
      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;
    }
};