leetcode.239. Sliding Window Maximum

来源:互联网 发布:ajax.js 代码下载 编辑:程序博客网 时间:2024/05/24 06:19

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 thek numbers in the window. Each time the sliding window moves right by one position.

For example,
Given nums = [1,3,-1,-3,5,3,6,7], and k = 3.

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

Therefore, return the max sliding window as [3,3,5,5,6,7].

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

Follow up:
Could you solve it in linear time?


class Solution {public:    vector<int> maxSlidingWindow(vector<int>& nums, int k) {       vector<int> result;       int size = nums.size();        if(size <= 0 || k <= 0)       {            return result;                   }//if        // 双向队列        deque<int> deque;       for(int i = 0;i < k;++i)       {           // 删除小于等于当前元素的值 例如 4 2 1 5            while(!deque.empty() && nums[i] >= nums[deque.back()])           {                deque.pop_back();            }//while            deque.push_back(i);                   }//for               for(int i = k-1;i < size;++i)        { // 删除小于等于当前元素的值             while(!deque.empty() && nums[i] >= nums[deque.back()])            {                 deque.pop_back();             }//while             // 不在滑动窗口之内             while(!deque.empty() && i - deque.front() >= k)            {                 deque.pop_front();                             }//while             deque.push_back(i);            result.push_back(nums[deque.front()]);        }//for         return result;    }};

0 0
原创粉丝点击