剑指offer—滑动窗口的最大值

来源:互联网 发布:iphone看片软件 编辑:程序博客网 时间:2024/04/28 16:46

题目描述
给定一个数组和滑动窗口的大小,找出所有滑动窗口里数值的最大值。例如,如果输入数组{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.ArrayList;import java.util.Deque;import java.util.LinkedList;public class Solution {    public ArrayList<Integer> maxInWindows(int [] num, int size)    {        ArrayList<Integer> res = new ArrayList<Integer>();        if(num==null || size>num.length || size<=0) return res;        Deque<Integer> queue = new LinkedList<Integer>();        for(int i=0; i<num.length; i++){            if(queue.isEmpty()) queue.offerLast(i);            int temp = queue.peekLast();            while(!queue.isEmpty() && num[i]>=num[temp]){                queue.pollLast();                if(!queue.isEmpty()){                    temp = queue.peekLast();                }            }            queue.offerLast(i);            if(i>=size-1){                int temp1 = queue.peekFirst();                if(i-temp1>=size){                    queue.pollFirst();                    temp1 = queue.peekFirst();                }                res.add(num[temp1]);            }        }        return res;    }}

思路:利用一个双端队列,队列的首元素永远是滑动窗口的最大值每次滑动的时候,如果新来的值小于队尾元素则将该元素加入,因为前面的元素滑动过后该元素有可能成为最大的值,如果新来的元素大于队尾元素,则删除队列中的元素,直到队列中的新队尾元素大于当前滑动的元素。在这之中有一个问题就是怎么样判断当前对首元素是不是目前滑动窗口的最大值呢?万一滑动窗口已经划过这个最大值了呢?这个问题通过使用将数组元素的下标值而不是元素值存入队列,当数组滑动的下标志减去队列下标值大于等于size,那么删除对首元素

原创粉丝点击