思路:
使用一个单调递减栈保存数组下标,用单调递减栈的原因是为了使栈的最左是当前窗口的最大值,如果用递增栈无法保证栈的右边是当前栈的最大值。
循环遍历如果数据过期就弹出保证当前栈的最左边是该窗口最大值的坐标。
import java.util.*; public class Solution { public ArrayList<Integer> maxInWindows(int [] num, int size) { ArrayList<Integer> list = new ArrayList<>(); LinkedList<Integer> stack = new LinkedList<>(); if(size==0||num.length==0||size>num.length)return list; for (int i = 0; i < size; i++) { while(!stack.isEmpty()&&num[stack.peekLast()]<num[i]){ stack.pollLast(); } stack.add(i); } list.add(num[stack.peekFirst()]); for (int i = 1; i < num.length-size+1 ; i++) { while(!stack.isEmpty()&&i>stack.peekFirst()){ stack.pollFirst(); } while(!stack.isEmpty()&&num[stack.peekLast()]<num[i+size-1]){ stack.pollLast(); } stack.addLast(i+size-1); list.add(num[stack.peekFirst()]); } return list; } }