题目描述
给定一个数组和滑动窗口的大小,找出所有滑动窗口里数值的最大值。例如,如果输入数组{2,3,4,2,6,2,5,1}及滑动窗口的大小3,那么一共存在6个滑动窗口,他们的最大值分别为{4,4,6,6,6,5}; 针对数组{2,3,4,2,6,2,5,1}的滑动窗口有以下6个: {[2,3,4],2,6,2,5,1}, {2,[3,4,2],6,2,5,1}, {2,3,[4,2,6],2,5,1}, {2,3,4,[2,6,2],5,1}, {2,3,4,2,[6,2,5],1}, {2,3,4,2,6,[2,5,1]}。
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
public class Solution {
public ArrayList<Integer> maxInWindows(int[] num, int size) {
ArrayList<Integer> array = new ArrayList<Integer>();
if(num == null || num.length == 0)
return array;
if(num.length < size)
return array;
if(size < 1)
return array;
Deque<Integer> deque = new ArrayDeque<Integer>();
for(int i = 0; i < size - 1; i++) {
while(!deque.isEmpty()) {
if(num[i] > num[deque.peekLast()]) {
deque.pollLast();
}else {
break;
}
}
deque.addLast(i);
}
for(int i = size - 1; i < num.length; i++) {
while(!deque.isEmpty()) {
if(num[i] > num[deque.peekLast()]) {
deque.pollLast();
}else {
break;
}
}
deque.addLast(i);
array.add(num[deque.peekFirst()]);
int j = deque.peekFirst();
if( i -j >= size - 1)
deque.pollFirst();
}
return array;
}
}