首页 > 其他 > 详细

209. Minimum Size Subarray Sum

时间:2017-03-02 13:10:32      阅读:172      评论:0      收藏:0      [点我收藏+]

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.

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

 本题目因为数组元素都是正数,没有有正有负的难,代码如下:

 1 public class Solution {
 2     public int minSubArrayLen(int s, int[] nums) {
 3         int len = nums.length;
 4         int left = -1;
 5         int sum = 0;
 6         int key = 0;
 7         for(int i=0;i<nums.length;i++){
 8             key+=nums[i];
 9             sum+=nums[i];
10             if(sum>=s){
11                 while(sum-nums[left+1]>=s){
12                     sum-=nums[++left];
13                 }
14                 len = Math.min(len,i-left);
15             }
16         }
17         if(key<s) return 0;
18         return len;
19     }
20 }

 

 

209. Minimum Size Subarray Sum

原文:http://www.cnblogs.com/codeskiller/p/6489865.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!