題目:
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: 2 Explanation: 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).
分析:
這個題如果只考慮O(n)的解法,就是道easy難度的題目,因爲就變成了典型的滑動窗口,設置兩個變量end,start,每次先滑動窗口的end,直到sum>=s爲止,然後滑動start使得sum小於s爲止,記錄此時end與start差,維護最小長度,繼續滑動窗口直到end到達邊界.
顯然複雜度爲O(n),因爲end變量是一直在動的,而start又受制於end變化,外層僅有end的遍歷.
考慮O(nlogn)的複雜度,由於有logn,一般是用二分法,接下來就是如何二分的問題,我們可以考慮用連續值sum來判斷,代碼寫得很詳細了,可以看代碼.
代碼:
public class Solution{
public int minSubArrayLen(int s,int [] nums){
return solveNlogN(s,nums);
}
private int solveNlogN(int s,int [] nums){
int [] sums = new int[nums.length+1];
// init the sums
for(int i=1;i<sums.length;i++){
sums[i]=sums[i-1]+nums[i-1];
}
int minLen = Integer.MAX_VALUE;
//二分查找序列
for(int i=0;i<sums.length;i++){
int end=binarySearch(i+1,sums.length-1,sums[i]+s,sums);
if(end==sums.length){
break;
}
minLen=Math.min(minLen,end-i);
}
return minLen==Integer.MAX_VALUE?0:minLen;
}
private int binarySearch(int lo,int hi,int key,int [] sums){
while(lo<=hi){
int mid = (lo+hi)/2;
if(sums[mid]>=key){
hi=mid-1;
}
else {
lo=mid+1;
}
}
return lo;
}
private int solveN(int s,int [] nums){
int start=0,end=0,sum=0,minLen=Integer.MAX_VALUE;
while(end<nums.length){
while(end<nums.length&&sum<s){
sum+=nums[end++];
}
if(sum<s)
break;
while(start<end&&sum>=s){
sum-=nums[start++];
}
minLen=Math.min(minLen,end-start+1);
}
return minLen==Integer.MAX_VALUE?0:minLen;
}
}