209. Minimum Size Subarray Sum

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.

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

7/5/2017
好久不刷题了,居然还能一遍过!
2ms, 72%, O(N)
 1 public class Solution {
 2     public int minSubArrayLen(int s, int[] nums) {
 3         int start = 0;
 4         int sum = 0;
 5         int minLength = nums.length + 1;
 6         for (int i = 0; i < nums.length; i++) {
 7             sum += nums[i];
 8             if (sum >= s) {
 9                 int length = i - start + 1;
10                 if (length < minLength) {
11                     minLength = length;
12                 }
13                 while (start <= i) {
14                     sum -= nums[start];
15                     start++;
16                     if (sum < s) {
17                         break;
18                     } else if (i - start + 1 < minLength) {
19                         minLength = i - start + 1;
20                     }
21                 }
22             }
23         }
24         if (minLength == (nums.length + 1)) {
25             return 0;
26         }
27         return minLength;
28     }
29 }

O(NlgN)记得算法书上有类似,divide & conquer,左边,右边,包含中间分别找最小的,代码不太会做。(这个想法好像不太对。。。)

官方解答:

https://leetcode.com/articles/minimum-size-subarray-sum/

O(NlgN)不是很好理解

别人的解法

思路解释得不错

https://discuss.leetcode.com/topic/13749/two-ac-solutions-in-java-with-time-complexity-of-n-and-nlogn-with-explanation

https://discuss.leetcode.com/topic/17063/4ms-o-n-8ms-o-nlogn-c

更多讨论

https://discuss.leetcode.com/category/217/minimum-size-subarray-sum

posted @ 2017-07-06 02:09  panini  阅读(123)  评论(0编辑  收藏  举报