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

Minimum Size Subarray Sum

时间:2016-07-01 06:45:20      阅读:188      评论: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 -1 instead.

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.

分析:

这里类似于在array上面放一个window, window的左边从第一个数开始,增加window的size, 保证window里的数之和大于S,然后每当window 右边往前走一步(window变大),就check是否可以把window左边cover的值remove掉(window 变小),并同时update minLength.

 1 public class Solution {
 2     /**
 3      * @param nums: an array of integers
 4      * @param s: an integer
 5      * @return: an integer representing the minimum size of subarray
 6      * cnblogs.com/beiyeqingteng/     * 
 7      */
 8     public int minimumSize(int[] nums, int s) {
 9         if (nums == null || nums.length == 0) return -1;
10         int start = 0;
11         int total = 0;
12         int minLength = Integer.MAX_VALUE;
13         for (int end = 0; end < nums.length; end++) {
14             total += nums[end];
15             if (total == s && minLength == Integer.MAX_VALUE) {
16                 minLength = end - start + 1;
17             }
18             while (start <= end && total - nums[start] >= s ) {
19                 total -= nums[start];
20                 start++;
21                 if (minLength > end - start + 1) {
22                     minLength = end - start + 1;
23                 }
24             }
25         }
26         
27         if (total < s) return -1;
28         return minLength;
29     }
30 }

转载请注明出处:cnblogs.com/beiyeqingteng/

Minimum Size Subarray Sum

标签:

原文地址:http://www.cnblogs.com/beiyeqingteng/p/5631737.html

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