剑指offer 滑动窗口的最大值

题目描述
给定一个数组和滑动窗口的大小,找出所有滑动窗口里数值的最大值。例如,如果输入数组{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]}。

这个题也不错。了解了关于双向队列的知识
1.加入队列时 把比它小的数全部出队列(因为这些数不可能成为最大数)

2.每次移动时,判断最大值是否从窗口中移出

此时队列其实是按照从小到大排序的

public ArrayList<Integer> maxInWindows(int [] num, int size)
    {
        ArrayList<Integer> list = new ArrayList<>();
        if(size <= 0 || size > num.length) return list;
        ArrayDeque<Integer> queue = new ArrayDeque<>();
        for (int i = 0; i < size; i++) {
            while((!queue.isEmpty()) && queue.peekLast() < num[i]){
                queue.pollLast();
            }
            queue.add(num[i]);
        }
        list.add(queue.peek());
        for (int i = size; i < num.length;i++){
            if(num[i - size] == queue.peek()) queue.poll();
            while((!queue.isEmpty()) && queue.peekLast() < num[i]){
                queue.pollLast();
            }
            queue.add(num[i]);
            list.add(queue.peek());
        }
        return list;

    }

猜你喜欢

转载自blog.csdn.net/ymybxx/article/details/79935190
今日推荐