滑动窗口的最大值
2016-04-08 22:50
232 查看
网址:点击打开链接
思路:先求出第一个窗口的最大值,并记录其下标。之后的每一个窗口的计算,都可以利用前一个窗口的计算结果(若前一个窗口的最大值的下标位于当前窗口内,而且此发生的概率为(k-1)/k,k越大其可能性越高),只需比较前一个窗口的最大值和当前窗口的最后一个值即可得出当前窗口的最大值。
代码:
思路:先求出第一个窗口的最大值,并记录其下标。之后的每一个窗口的计算,都可以利用前一个窗口的计算结果(若前一个窗口的最大值的下标位于当前窗口内,而且此发生的概率为(k-1)/k,k越大其可能性越高),只需比较前一个窗口的最大值和当前窗口的最后一个值即可得出当前窗口的最大值。
代码:
public class Solution { /** * @param nums: A list of integers. * @return: The maximum number inside the window at each moving. */ public ArrayList<Integer> maxSlidingWindow(int[] nums, int k) { // write your code here ArrayList<Integer> R = new ArrayList<Integer>(); if(nums.length < k||k==0) return R; int max=Integer.MIN_VALUE,id=0; for(int i=0;i<k&&i<nums.length;++i) if(nums[i]>max){ max = nums[i]; id = i; } R.add(max); for(int i=k;i<nums.length;++i){//end with k if(id>i-k){ if(max < nums[i]){ max = nums[i]; id = i; } R.add(max); }else{ max = Integer.MIN_VALUE; for(int j=i-k+1;j<=i;++j) if(nums[j]>max){ max = nums[j]; id = j; } R.add(max); } } return R; } }
相关文章推荐
- synchronized,lock
- C连接MySQL数据库开发之Xcode环境配置及测试
- STL学习系列五:Queue容器
- andorid 数据储存
- Linux中进程正常退出return和exit()的区别
- JZOJ3221. 【HNOI2013】游走
- 《NPS Training》学习分享
- cocos2d-x 2.x粒子系统
- 关于python中的unicode字符串的使用
- 关于python中的unicode字符串的使用
- Git回滚远程版本
- Codeforces Round #149 (Div. 2) E. XOR on Segment (线段树成段更新+二进制)
- STL配置器(四)----内存池技术
- hdu1796(容斥原理)
- 该网站的安全证书吊销信息不可用
- 无比奇怪的问题,Runtime报错,程序仍可运行(有可能是线程崩溃,但主程序不崩溃,线程崩溃可能是因为锁使用不当引起的)
- URAL 1991 The battle near the swamp 水题
- andorid 多线程handler用法
- MyBatis (7)——Mybatis缓存
- poj3069 贪心