209. Minimum Size Subarray Sum
Posted panini
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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.
If you have figured out the O(n) solution, try coding another solution of which the time complexity is O(n log 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/17063/4ms-o-n-8ms-o-nlogn-c
更多讨论
https://discuss.leetcode.com/category/217/minimum-size-subarray-sum
以上是关于209. Minimum Size Subarray Sum的主要内容,如果未能解决你的问题,请参考以下文章
209. Minimum Size Subarray Sum
209. Minimum Size Subarray Sum
209. Minimum Size Subarray Sum
209. Minimum Size Subarray Sum