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

class Solution {
public:
	int minSubArrayLen(int s, vector<int>& nums) {
		int sum=0;
		for(int i=0;i<nums.size();i++)
		{
			if(nums[i]>=s)
				return 1;
			sum+=nums[i];
		}
		if(sum<s)
			return 0;
		int minnum=nums.size();
		for(int i=0;i<nums.size()-1;i++)
		{
			sum=0;
			int k=i;
			while(k<nums.size()&&sum<s&&k-i<minnum)
			{
				sum+=nums[k];
				k++;
			}
			if(sum>=s&&k-i<minnum)
				minnum=k-i;
		}
		return minnum;
	}
};

accepted

你可能感兴趣的:(LeetCode)