滑動(dòng)窗口應(yīng)用場景:
最長連續(xù)子串等、最小和連續(xù)子集等問題,和動(dòng)規(guī)的區(qū)別是動(dòng)規(guī)可以劃分出子集;
思維導(dǎo)圖:

舉例:
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跳出循環(huán)的情況
????????????????min = Math.min(min,j-i);????????????
????????????sum-=nums[i];
? ? ? ? }
????????return min==Integer.MAX_VALUE? -1: min;//邊界條件考慮,為空的時(shí)候,無解的時(shí)候
????}
}