滑动窗口的最大值

滑动窗口的最大值

https://www.nowcoder.com/practice/1624bc35a45c42c0bc17d17fa0cba788?tpId=13&tqId=11217&rp=1&ru=%2Fta%2Fcoding-interviews&qru=%2Fta%2Fcoding-interviews%2Fquestion-ranking&tab=answerKey

双指针向右滑动,然后遍历比较找出滑动窗口里面的最大值

public ArrayList<Integer> maxInWindows(int [] num, int size)
    {
        ArrayList<Integer> res = new ArrayList<>();
        if(num.length < size || num.length == 0 || size < 1)
            return res;
        int l = 0;
        int r = size-1;
        while(r <= num.length-1){
            int max = num[l];
            for(int i = l; i <= r; i++){
                if(max < num[i])
                    max = num[i];
            }
            res.add(max);
            l++;
            r++;
        }
        return res;
    }

借助一个大顶堆,存储滑动窗口的元素,然后取堆顶的数即为滑动窗口的最大值,然后滑动窗口往下滑一个位置

public ArrayList<Integer> maxInWindows(int [] num, int size)
    {
        PriorityQueue<Integer> maxQueue = new PriorityQueue<Integer>((o1,o2)->o2-o1); // 大顶堆
        ArrayList<Integer> res = new ArrayList<>();
        if(num.length < size || num.length == 0 || size < 1)
            return res;
        int index = 0;
        for(;index < size; index++)  // 先初始化第一个滑动窗口
            maxQueue.add(num[index]);

        while(index < num.length){  //当滑到最后一个时
            res.add(maxQueue.peek());  //堆顶即为最大
            maxQueue.remove(num[index-size]);  //移除掉滑动窗口第一个元素
            maxQueue.add(num[index]);  //加进去当前位置的元素
            index++;   
        }
        res.add(maxQueue.peek());  // 最后一个没放进去
        return res;
    }
剑指offer 文章被收录于专栏

为刷过的每一道题都书写一篇题解,便于重复练习~

全部评论

相关推荐

05-05 21:45
已编辑
广州大学 Java
点赞 评论 收藏
分享
评论
2
1
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务