标签:
题目:
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.
思路:left、right两个指针,sum小于s的时候,right++,大于s的时候,left++,维护好sum的值即可,同时要判断数组的总和是否满足。
代码:
public class Solution { public int minSubArrayLen(int s, int[] nums) { int left = 0 ; int right = 0; int min = Integer.MAX_VALUE; int sum = 0; while(left <= right && right < nums.length){ sum += nums[right]; while(sum >= s && left <= right){ if(right - left + 1 < min) min = right - left + 1; sum -= nums[left]; left++; } right++; } if(min == Integer.MAX_VALUE) return 0; return min; } }
[LeetCode-JAVA] Minimum Size Subarray Sum
标签:
原文地址:http://www.cnblogs.com/TinyBobo/p/4545796.html