leedcode239. Sliding Window Maximum

public int[] maxSlidingWindow(int[] nums, int k) {
       ArrayDeque deque = new ArrayDeque(nums.length);
       int []end = new int[nums.length];
       int index = 0;


       for(int i = 0 ; i < nums.length ; i ++)
       {
           //删除deque,当左边缘满足条件时
           if(!deque.isEmpty() && (Integer)deque.getLast() == i - k) deque.pollFirst();
           //每次要加入deque push都要和右边比较,右边缘小则pop出去,这样保证了deque左边一直是最大的
           while(!deque.isEmpty() && nums[(Integer)deque.getLast()] <= nums[i])
               deque.pollLast();
           deque.addLast((Integer)i);
           //左边一直是最大的
           if(i - k + 1 >= 0)  end[index ++] = nums[(Integer)deque.getFirst()];
       }


       int []last = new int[index];
       for(int i = 0 ; i < index  ; i ++)
           last[i] = end[i];
       return last;
    }
点赞