209. Minimum Size Subarray Sum

2018/05/15 leetcode 共 645 字,约 2 分钟

title

link 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: [2,3,1,2,4,3], s = 7

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

solution

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

Search

    Table of Contents