Given an array ofnpositive integers and a positive integers, find the minimal length of a subarray of which the sum ≥s. If there isn't one, return 0 instead.
For example, given the array[2,3,1,2,4,3]ands = 7,the subarray[4,3]has the minimal length under the PRoblem constraint.
這道題主要還是先要把題目的要求弄清楚。首先題目中所說的if there is not one, return 0 instead。怎樣才算是沒有呢?
這里意思是如果我們算出來的min length和array本身的長度一樣,那么我們就應該return 0。
這里比較容易想到的是用two pointer來計算。一個pointer用來計算sum,和另一個pointer緊隨其后,用來判斷長度。
代碼如下。~
public class Solution { public int minSubArrayLen(int s, int[] nums) { //two pointer //one from start;one follows int start = 0; int end = 0; int sum = 0; int min = nums.length; while(start<nums.length && end<nums.length) { while(sum<s && end<nums.length) { sum=sum+nums[end]; end++; } while(sum>=s && start<=end) { min = Math.min(min, end-start); sum =sum-nums[start]; start++; } } if(min==nums.length){ return 0; } return min; }}新聞熱點
疑難解答