题解 | #滑动窗口的最大值#

滑动窗口的最大值

https://www.nowcoder.com/practice/1624bc35a45c42c0bc17d17fa0cba788

思路

本题思路其实不难,使用两个变量,一个存储窗口的首位置,另外一个存储窗口中的最大值,使用while循环更新窗口首位置,使用for循环从窗口首位置遍历size长度,比较出的最大值加入集合最后返回即可。具体请看代码注释

代码

import java.util.*;
public class Solution {
    public ArrayList<Integer> maxInWindows(int [] num, int size) {
        // 创建集合存储滑动窗口的最大值
        ArrayList<Integer> windowMaximums = new ArrayList<>();
        // 对传入值做校验,窗口大于数组长度或窗口长度为0的时候,返回空集合(别问我为什么不返回null)。
        if (num.length < size || size == 0) {
            return windowMaximums;
        }
        // 创建变量标记窗口首位置
        int headLocation = 0;
        // 创建变量标记窗口最大值
        int windowMaximum = Integer.MIN_VALUE;
        // 使用while循环更新窗口首位置,窗口首位置不应超过数组长度减去窗口长度
        while (headLocation <= num.length - size) {
            // 使用for循环遍历窗口,寻找窗口最大值
            for (int i = headLocation; i < headLocation + size; i++) {
                if (windowMaximum < num[i]) {
                    windowMaximum = num[i];
                }
            }
            // 循环结束后更新窗口首位置
            headLocation++;
            // 将最大值加入集合
            windowMaximums.add(windowMaximum);
            // 重置最大值
            windowMaximum = Integer.MIN_VALUE;
        }
        return windowMaximums;
    }
}
全部评论

相关推荐

头像
04-29 10:53
已编辑
东北大学 自动化类
点赞 评论 收藏
转发
点赞 收藏 评论
分享
牛客网
牛客企业服务