LeetCode(239):滑动窗口最大值 Sliding Window Maximum(Java)

本文介绍了如何使用动态规划和双向链表解决LeetCode中的239题——滑动窗口最大值问题。通过创建双向队列并不断更新,以及子块分割的方法,实现O(n)的时间复杂度找到窗口内最大值。
摘要由CSDN通过智能技术生成

2019.9.20 #程序员笔试必备# LeetCode 从零单刷个人笔记整理(持续更新)

又是一道LeetCode刷新剑指Offer题,这道滑动窗口最大值可以有两种o(n)的方法:

动态规划 + 双向链表

创建双向队列list,每次遍历将小于nums[i]的队首元素出列,并将i放入队首。删去过期元素(超出窗口)后的队尾即为当前窗口元素最大值。思路可以参考之间写过的:#数据结构与算法学习笔记#剑指Offer62:滑动窗口的最大值 + 在线处理(Java、C/C++)

动态规划 + 子块分割

这种方法非常巧妙。将数组分为长度为k的若干子块,创建动态规划数组:

1.left[i]代表从块首至i的元素最大值,动态转移方程为Math.max(left[i - 1], nums[i]);

2.right[j]代表从块尾至j的元素最大值,动态转移方程为Math.max(right[j + 1], nums[j]);

长度为k的窗口i-j的最大值为Math.max(right[i], left[j]),有两种情况:

1.如果恰为子块之一,那最大值 = right[i] = left[j]

2.若跨a-b子块,则right[i]为a子块中的最大值,left[j]为b子块中的最大值,取较大者即可。


传送门:滑动窗口最大值

Given an array nums, there is a sliding window of size k which is moving from the very left of the array to the very right. You can only see the k numbers in the window. Each time the sliding window moves right by one position. Return the max sliding window.

给定一个数组 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

提示:你可以假设 k 总是有效的,在输入数组不为空的情况下,1 ≤ k ≤ 输入数组的大小。

进阶:你能在线性时间复杂度内解决此题吗?


import java.util.LinkedList;

/**
 *
 * Given an array nums, there is a sliding window of size k which is moving from the very left of the array to the very right.
 * You can only see the k numbers in the window. Each time the sliding window moves right by one position. Return the max sliding window.
 * 给定一个数组 nums,有一个大小为 k 的滑动窗口从数组的最左侧移动到数组的最右侧。你只可以看到在滑动窗口内的 k 个数字。滑动窗口每次只向右移动一位。
 * 返回滑动窗口中的最大值。
 *
 */

public class SlidingWindowMaximum {
   

    //动态规划 + 双向链表
    public int[] maxSlidingWindow(int[] nums, int k) {
   
        if(nums.length == 0 || k == 0){<
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值