LeetCode-Minimum Size Subarray Sum-解题报告

原创 2015年07月08日 18:12:41

原题链接 https://leetcode.com/problems/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. 


设置有一个start和sum,然后遍历数组,当 sum>= s 的时候,start往后走,直到 sum 不小于 s,更新start。


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

		}
		return ans > nums.size()? 0 : ans - 1;
	}
};


[Leetcode] 325. Maximum Size Subarray Sum Equals k 解题报告

题目: Given an array nums and a target value k, find the maximum length of a subarray that sums t...

【LeetCode】560.Subarray Sum Equals K解题报告

【LeetCode】560.Subarray Sum Equals K解题报告tags: Array 题目地址:https://leetcode.com/problems/subarray-sum-e...

LeetCode 523. Continuous Subarray Sum 解题报告

LeetCode 523. Continuous Subarray Sum 解题报告题目描述Given a list of non-negative numbers and a target inte...

Leetcode——209. Minimum Size Subarray Sum

题目: Given an array of n positive integers and a positive integer s, find the minimal length of a co...

Leetcode 209 - Minimum Size Subarray Sum(二分 or 双指针)

题意给一个数组a[]和一个数s,要求在a里面找到一个长度最短的连续子序列,并且子序列的和大于等于s。思路算法1前缀和 + 二分。时间复杂度O(nlogn)O(nlogn)。我们先维护一个前缀和ss,然...
  • Lzedo
  • Lzedo
  • 2017年02月12日 20:35
  • 117

Minimum Size Subarray Sum - LeetCode 209

题目描述: Given an array of n positive integers and a positive integer s, find the minimal length of a ...
  • bu_min
  • bu_min
  • 2015年05月24日 20:52
  • 216

LeetCode 209. Minimum Size Subarray Sum 滑动窗口

一、题目 Given an array of n positive integers and a positive integer s, find the minimal length of a ...

[Leetcode]Minimum Size Subarray Sum

Given an array of n positive integers and a positive integer s, find the minimal length of a subarr...

【leetcode】209. Minimum Size Subarray Sum

【leetcode】209. Minimum Size Subarray Sum

Leetcode209-Minimum Size Subarray Sum

Given an array of n positive integers and a positive integer s, find the minimal length of a subarra...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:LeetCode-Minimum Size Subarray Sum-解题报告
举报原因:
原因补充:

(最多只允许输入30个字)