博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
【13】239. Sliding Window Maximum
阅读量:4313 次
发布时间:2019-06-06

本文共 1692 字,大约阅读时间需要 5 分钟。

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
maxSlidingWindow(vector
& nums, int k) { 4 vector
res; 5 deque
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 index10 if(i >= k - 1) res.push_back(nums[q.front()]);11 }12 return res;13 }14 };

 

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

转载于:https://www.cnblogs.com/93scarlett/p/6362423.html

你可能感兴趣的文章
使用case语句给字体改变颜色
查看>>
JAVA基础-多线程
查看>>
面试题5:字符串替换空格
查看>>
JSP九大内置对象及四个作用域
查看>>
ConnectionString 属性尚未初始化
查看>>
数据结构-栈 C和C++的实现
查看>>
发布功能完成
查看>>
MySQL基本命令和常用数据库对象
查看>>
poj 1222 EXTENDED LIGHTS OUT(位运算+枚举)
查看>>
秘密:之所以不搞军事同盟,俄罗斯
查看>>
进程和线程概念及原理
查看>>
Lucene、ES好文章
查看>>
后视镜应该这样用!能帮避免80%的车祸!
查看>>
PDB调试python代码常用命令
查看>>
web性能优化-浏览器渲染原理
查看>>
Java第七次作业
查看>>
配置consul为windows服务
查看>>
架构之美阅读笔记02
查看>>
Mac中安装Vim7.4
查看>>
VC++工程文件说明
查看>>