码迷,mamicode.com
首页 > 编程语言 > 详细

LeetCode 209 Minimum Size Subarray Sum 最小子数组和问题

时间:2019-02-10 12:29:27      阅读:207      评论:0      收藏:0      [点我收藏+]

标签:题目   int   max   span   ima   ring   follow   print   instead   

Given an array of n positive integers and a positive integer s, find the minimal length of a contiguoussubarray of which the sum ≥ s. If there isn‘t one, return 0 instead.

Example: 

Input: s = 7, nums = [2,3,1,2,4,3]
Output: 2
Explanation: the subarray [4,3] has the minimal length under the problem constraint.
Follow up:
If you have figured out the O(n) solution, try coding another solution of which the time complexity is O(nlog n). 
 
思路:使用滑动窗口,窗口右侧先向右扩张,使用一个变量sum来记录窗口中数字的总和,当sum大于s的时候,窗口左侧右移来缩小窗口并将sum减去nums[left]。重复此操作直到right到达数组的末尾,而left到达临界值。
 
 
 1 public class Minimum_Size_Subarray_Sum {
 2     public static int minSubArrayLen(int s, int[] nums) {
 3         if(null==nums||nums.length==0){
 4             return 0;
 5         }
 6         
 7         int left = 0;
 8         int minLeft = 0;
 9         int minLen = nums.length;
10         int sum = 0;
11         int maxSum = Integer.MIN_VALUE;
12         
13         for(int right=0;right<nums.length;right++){
14             if(sum<s){
15                 sum += nums[right];
16                 if(sum>maxSum){
17                     maxSum = sum;
18                 }
19             }
20             
21             while(sum>=s){
22                 if(right-left+1<minLen){
23                     minLeft = left;
24                     minLen = right - left + 1;
25                 }
26                 
27                 sum -= nums[left];
28                 left++;
29             }
30         }
31         
32         if(maxSum<s){
33             return 0;
34         }
35         
36         return minLen;
37     }
38     
39     public static void main(String[] args) {
40         int[] nums = {1,1,1,1,1,1};
41         System.out.println(minSubArrayLen(6, nums));
42         
43     }
44 }

 

类似题目:

   窗口最小子串问题  https://www.cnblogs.com/blzm742624643/p/10357757.html

LeetCode 209 Minimum Size Subarray Sum 最小子数组和问题

标签:题目   int   max   span   ima   ring   follow   print   instead   

原文地址:https://www.cnblogs.com/blzm742624643/p/10359029.html

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