美文网首页
Sliding Window Maximum

Sliding Window Maximum

作者: Wenyue_offer | 来源:发表于2017-09-14 07:43 被阅读0次
Screen Shot 2017-09-13 at 16.42.48.png
public class Solution {
    public int[] maxSlidingWindow(int[] nums, int k) {
        if(nums == null || nums.length < k || k <= 0) return new int[0];
        int n = nums.length;
        int[] res = new int[n - k + 1];
        int ri = 0;
        Deque<Integer> deque = new LinkedList<>();
        for(int i = 0; i < n ; i++)
        {
            while(!deque.isEmpty() && deque.peekFirst() < i - k + 1) deque.pollFirst();
            while(!deque.isEmpty() && nums[deque.peekLast()] < nums[i]) deque.pollLast();
            deque.offerLast(i);
            if(i >= k - 1) res[ri++] = nums[deque.peekFirst()];
        }
        return res;
    }
}

相关文章

网友评论

      本文标题: Sliding Window Maximum

      本文链接:https://www.haomeiwen.com/subject/mtyrsxtx.html