码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcode: Minimum Size Subarray Sum

时间:2015-12-17 08:13:10      阅读:142      评论:0      收藏:0      [点我收藏+]

标签:

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

Haven‘t think about the O(nlogn) solution.

O(n) solution is to maintain a window

 1 public class Solution {
 2     public int minSubArrayLen(int s, int[] nums) {
 3         int minWin = Integer.MAX_VALUE;
 4         int l=0, r=0;
 5         if (nums==null || nums.length==0) return 0;
 6         int sum = 0;
 7         while (r < nums.length) {
 8             sum += nums[r];
 9             while (sum >= s) {
10                 minWin = Math.min(minWin, r-l+1);
11                 sum -= nums[l++];
12             }
13             r++;
14         }
15         if (r==nums.length && l==0 && sum<s) return 0;
16         return minWin;
17     }
18 }

Initially I‘m concerning I should maintain the window to have its sum always be >= s, and l should always fall at a place maintaining this property. But the solution above proves that I need not do this. Anyway, my solution also works as follows:

 1 public class Solution {
 2     public int minSubArrayLen(int s, int[] nums) {
 3         int minWin = Integer.MAX_VALUE;
 4         int l=0, r=0;
 5         if (nums==null || nums.length==0) return 0;
 6         int sum = 0;
 7         while (r < nums.length) {
 8             sum += nums[r];
 9             if (sum >= s) { //found one feasible window, try to shrink the window
10                 while (l<=r && sum-nums[l] >= s) {
11                     sum -= nums[l++];
12                 }
13                 minWin = Math.min(minWin, r-l+1);
14             }
15             r++;
16         }
17         if (r==nums.length && l==0 && sum<s) return 0;
18         return minWin;
19     }
20 }

 

Leetcode: Minimum Size Subarray Sum

标签:

原文地址:http://www.cnblogs.com/EdwardLiu/p/5052889.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!