滑动窗口

作者: 米拉在西糊 | 来源:发表于2020-03-10 23:40 被阅读0次

滑动窗口应用场景:

最长连续子串等、最小和连续子集等问题,和动规的区别是动规可以划分出子集;

思维导图:


举例:

209. Minimum Size Subarray Sum

Given an array of n positive integers and a positive integer s, find the minimal length of a contiguous subarray of which the sum ≥ s. If there isn't one, return 0 instead.

Example: 

Input: s = 7, nums = [2,3,1,2,4,3]Output: 2Explanation: the subarray [4,3] has the minimal length under the problem constraint.

Follow up:

If you have figured out the O(n) solution, try coding another solution of which the time complexity is O(n log n). 

代码:

public class Solution {

    public int minimumSize(int[] nums, int s) {

        if(nums.length==0) return -1;

        int i=0,j=0;int min = Integer.MAX_VALUE,sum=0;

        for(i=0;i<nums.length;i++){

            //sum = nums[i];

            while(j<nums.length&&sum<s){

                sum+=nums[j];

                j++;                

            }

            if(sum>=s)//排除j>=n跳出循环的情况

                min = Math.min(min,j-i);            

            sum-=nums[i];

        }

        return min==Integer.MAX_VALUE? -1: min;//边界条件考虑,为空的时候,无解的时候

    }

}

相关文章

  • Algorithm进阶计划 -- 滑动窗口

    滑动窗口算法滑动窗口框架滑动窗口运用 1. 滑动窗口框架 滑动窗口算法,核心思路是维护一个窗口,不断滑动,然后更新...

  • TCP可靠传输理论;流量控制;拥塞控制

    滑动窗口、超时重传、选择确认SACK 滑动窗口 滑动窗口:发送窗口、接收窗口。发送窗口内的数据都可以发送,在收到新...

  • 3. 无重复字符的最长子串

    主要用到了滑动窗口算法两个指针之间就代表是一个滑动窗口,滑动窗口必须保证没有重复元素,同时保留最大的滑动窗口的大小...

  • Flutter-BottomSheet(底部滑动窗口)

    BottomSheet(底部滑动窗口) ModalBottomSheet(对话框式底部滑动窗口) BottomSh...

  • 无重复字符最长字串

    滑动窗口

  • (3)FlinkSQL滑动窗口demo演示

    滑动窗口(Sliding Windows)与滚动窗口类似,滑动窗口的大小也是固定的。区别在于,窗口之间并不是首尾相...

  • 滑动窗口

    406. 和大于S的最小子数组 描述给定一个由 n 个正整数组成的数组和一个正整数 s ,请找出该数组中满足其和 ...

  • 滑动窗口

    最长无重复字母子串 leetcode438

  • 滑动窗口

    介绍将TCP与UDP这样的简单传输协议区分开来的是它传输数据的质量。TCP对于发送数据进行跟踪,这种数据管理需要协...

  • 滑动窗口

    有一个整型数组 arr ,和一个大小为 w 的窗口从数组的最左边滑到最右边,窗口每次向右边滑一个位置。返回一个长度...

网友评论

    本文标题:滑动窗口

    本文链接:https://www.haomeiwen.com/subject/nylodhtx.html