209. Minimum Size Subarray Sum

problem description

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).

algorithm thought

这里求出连续子数组之和大于s的最小值。有两种方法,题目中follow up也提出,有O(n)和O(nlgn)的办法。

首先说下O(nlgn),这种形式的时间复杂度一般是分治法,类似的有归并排序。对于这题,连续数组要不就是包含中间那个值,或者是在左半数组中或者是在右半数组中。所以首先处理连续数组在中间的情况,从中间开始左右扩展,然后左边右边递归处理即可。最后得到最大的

然后是O(n)的解法,这里还是使用快慢指针,快的先加,如果超过了s,慢指针再往前,慢指针只需要减,直到小于s。直到快指针超过数组长度即可结束,中间每次比较得到最小值

code

class Solution {
public:
    int minSubArrayLen(int s, vector<int>& nums) {
        if(nums.size()==0)
            return 0;
        int fast=0,slow=0;
        int sum=0;
        int res=INT_MAX;
        while(fast<nums.size()){
            sum+=nums[fast];
            while(sum>=s){
                res=min(res,fast-slow+1);
                sum-=nums[slow++];    
            }
            fast++;
        }
        return res==INT_MAX?0:res;
    }
};

algorithm analysis

thought中已经分析了时间复杂度,这里就不多说了

Last updated