您的位置:首页 > 其它

滑动窗口的最大值

2016-04-08 22:50 232 查看
网址:点击打开链接

思路:先求出第一个窗口的最大值,并记录其下标。之后的每一个窗口的计算,都可以利用前一个窗口的计算结果(若前一个窗口的最大值的下标位于当前窗口内,而且此发生的概率为(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;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: