LeetCode 209 Minimum Size Subarray Sum

原创 2016年08月30日 13:06:42

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.

click to show more practice.

More practice:

If you have figured out the O(n) solution, try coding another solution of which the time complexity is O(n log n).

Runtime: 1 ms

O(n) time, O(1) space moving window method
using a moving window [left,i] to calculate the sum, first move i forward to get a sub-array with sum>=s, then move left forward to make sum < s, then move end again,..., until i reach the end of array.
	public int minSubArrayLen(int s, int[] nums) {
		int min = Integer.MAX_VALUE, left = 0;
		for (int i = 0; i < nums.length; i++) {
			s -= nums[i];
			while (s <= 0) {
				min = Math.min(min, i - left + 1);
				s += nums[left++];
			}
		}
		return min == Integer.MAX_VALUE ? 0 : min;
	}

版权声明:本文为博主原创文章,未经博主允许不得转载。

相关文章推荐

leetcode209-Minimum Size Subarray Sum(最小长度子数组和)

问题描述:Given an array of n positive integers and a positive integer s, find the minimal length of a su...

LeetCode 209. Minimum Size Subarray Sum (O(n)实现)

动态规划: len[i]:  - 若存在begin使得sum(nums.begin()+begin, nums.begin()+i+1)>=s且sum(nums.begin()+begin-1, nu...

【LeetCode】209. Minimum Size Subarray Sum

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

Leetcode 209 Minimum Size Subarray Sum

给出一个正整数数组,以及一个正整数s,找到最短的子数组且该子数组的和不小于s。如果不存在这样的子数组,返回0.

Leetcode 209. Minimum Size Subarray Sum

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

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

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】209. Minimum Size Subarray Sum

【leetcode】209. Minimum Size Subarray Sum
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:深度学习:神经网络中的前向传播和反向传播算法推导
举报原因:
原因补充:

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