滑动窗口最大值

给定一个数组 nums,有一个大小为 k 的滑动窗口从数组的最左侧移动到数组的最右侧。你只可以看到在滑动窗口内的 k 个数字。滑动窗口每次只向右移动一位。
返回滑动窗口中的最大值。
进阶:
你能在线性时间复杂度内解决此题吗?
输入: nums = [1,3,-1,-3,5,3,6,7], 和 k = 3
输出: [3,3,5,5,6,7]
解释:

滑动窗口的位置        最大值
-------------------------    -----
[1 3 -1] -3 5 3 6 7        3
1 [3 -1 -3] 5 3 6 7        3
1 3 [-1 -3 5] 3 6 7        5
1 3 -1 [-3 5 3] 6 7        5
1 3 -1 -3 [5 3 6] 7        6
1 3 -1 -3 5 [3 6 7]        7

提示:
1 <= nums.length <= 10^5
-10^4 <= nums[i] <= 10^4
1 <= k <= nums.length

public class MaxSlideWindowSolution {

    public static void main(String[] args) {
        int [] nums = {1,3,-1,-3,5,3,6,7};
        int k = 3;
        System.out.println(Arrays.toString(maxSlidingWindow(nums, k)));
    }

    public static int[] maxSlidingWindow(int[] nums, int k) {
        int[] res = new int[nums.length - k + 1];
        LinkedList<Integer> list = new LinkedList<>();
        int right = 0;
        int index = 0;
        while (right < nums.length) {
            // 把最大值放在list首位
            while (!list.isEmpty() && list.peekLast() < nums[right]) {
                list.removeLast();
            }

            list.add(nums[right++]);
            if (right >= k) {
                res[index++] = list.peekFirst();
                if (list.peekFirst() == nums[right - k]) {
                    list.removeFirst();
                }
            }
        }

        return res;
    }
}

 

posted @ 2022-07-26 19:34  牧 天  阅读(23)  评论(0)    收藏  举报