首页 > Windows开发 > 详细

239. Sliding Window Maximum

时间:2017-02-03 13:35:23      阅读:230      评论:0      收藏:0      [点我收藏+]

239. Sliding Window Maximum

  • Total Accepted: 49842
  • Total Submissions: 157784
  • Difficulty: Hard
  • Contributors: Admin 

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.

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?

Solution: (deque)
 
大概思路是用双向队列保存数字的下标,遍历整个数组,如果此时队列的首元素是i - k的话,表示此时窗口向右移了一步,则移除队首元素。然后比较队尾元素和将要进来的值,如果小的话就都移除,然后此时我们把队首元素加入结果中即可
 1 class Solution {
 2 public:
 3     vector<int> maxSlidingWindow(vector<int>& nums, int k) {
 4         vector<int> res;
 5         deque<int> q;
 6         for(int i = 0; i < nums.size(); i++){
 7             if(!q.empty() && q.front() == i - k) q.pop_front();
 8             while(!q.empty() && nums[q.back()] < nums[i]) q.pop_back();//while!!!! 只保留windows里面最大的在队首
 9             q.push_back(i);//deque save the index
10             if(i >= k - 1) res.push_back(nums[q.front()]);
11         }
12         return res;
13     }
14 };

 

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

239. Sliding Window Maximum

原文:http://www.cnblogs.com/93scarlett/p/6362423.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!