滑動(dòng)窗口

滑動(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í)候

????}

}

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容