209. Minimum Size Subarray Sum

Given an array of n positive integers and a positive integer s, 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] and s = 7,
the subarray [4,3] has the minimal length under the problem constraint.測試

題意就是要找出數組中的最短子數組,其和不小於給定值s。剛開始的想法很簡單,兩層循環,但耗時過多300ms。改進後,只需遍歷一次,維護兩個標誌low和high,讓low和high之間的子數組不小於給定值s,而後求最短,耗時4ms。另外,感受測試數據不夠全面,將求和值sum換爲int型,也能夠經過(本人覺得只是測試數據未考慮全面,若s=2^32-1,數組array[2^32-2,2],sum就會越界,因此建議sum定義爲long long 型)。spa

代碼1:code

 1 int minSubArrayLen(int s, vector<int>& nums)
 2 {
 3     int size=nums.size();
 4     if (size==0)
 5         return 0;
 6     int minLen=size+1;
 7     for (int i=0;i<size;i++)
 8     {
 9         int n=0;
10         long long sum=0;
11         for (int j=i;j<size;j++)
12         {
13             sum=sum+nums[j];
14             ++n;
15             if (sum>=s)
16             {
17                 if(minLen>n)
18                     minLen=n;
19                 break;
20             }
21         }
22     }
23     if(minLen==size+1)
24         return 0;
25     return minLen;
26 }

改進後代碼:blog

 1 int minSubArrayLen(int s, vector<int>& nums)
 2 {
 3     int size=nums.size();
 4     int minLen=size+1,low=0,high=0;
 5     long long sum=0;
 6     while(high<size)
 7     {
 8         sum+=nums[high];
 9         ++high;
10         while(sum>=s)
11         {
12             minLen=min(minLen,high-low);
13             sum-=nums[low];
14             ++low;
15         }
16     }
17     if(minLen==size+1)
18         return 0;
19     return minLen;
20 }
相關文章
相關標籤/搜索