leetcode239:Sliding Window Maximum
2015-07-19 16:00
316 查看
Given an array nums,there is a sliding window of size k whichis moving from the very left of the array to the very right. You can only see the k numbersin 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 31 [3 -1 -3] 5 3 6 7 31 3 [-1 -3 5] 3 6 7 51 3 -1 [-3 5 3] 6 7 51 3 -1 -3 [5 3 6] 7 61 3 -1 -3 5 [3 6 7] 7Therefore, 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?思路;这里用了Java中的双队列数据结构 Deque(实现类中的ArrayDeque)
public static int[] maxSlidingWindow(int[] nums,int k){if(k==0) //不要忘记特殊情况return null;int[] results = new int[nums.length-k+1];Deque<Integer> deque = new ArrayDeque<Integer>(); //Integer不能用intint count = 0;for(int i=0;i<nums.length;i++){//deque中存储的元素:是当前窗口内的元素中的几个,且得保证队首是窗口中最大元素while(!deque.isEmpty() && nums[i]>deque.getLast())deque.pollLast();deque.add(nums[i]);if(i>=k-1){ //从第K-1个元素开始,窗口已满,先滑出,再滑入results[count++] = deque.getFirst();if(nums[i-k+1]==deque.getFirst()){deque.pollFirst(); //滑出的正好是窗口内元素最大的,deque弹出}}}return results;}
相关文章推荐
- 欢迎使用CSDN-markdown编辑器
- 百度,360 你们谁是骗子?
- 编程中应注意的细节
- hdu 2141 Can you find it? 二分
- CAS
- Swap Nodes in Pairs
- 算法总结——spfa(使用优先队列的Bellman_Ford算法)
- Struts2乱码问题的解决办法
- Ubuntu输入密码登陆后又跳回到登录界面
- JavaScript--DOM修改元素的属性
- 黑马程序员——Java反射&动态代理
- 龙贝格算法
- 关于ListView中ViewHolder修饰符的问题
- Ubuntu 14.10 下Hadoop HttpFS 配置
- 菜鸟学习OpenCV(Python)碰到的一些小问题
- stack smashing detected报错
- LeetCode#189 Rotate Array
- [LeetCode] Find Minimum in Rotated Sorted Array
- Tomcat监控xml ,当修改xml后,不用重启tomcat
- 多态的覆盖(重写)