Leetcode——209. Minimum Size Subarray Sum

题目原址

https://leetcode.com/problems/minimum-size-subarray-sum/description/

题目描述

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.
Example:

Input: [2,3,1,2,4,3], s = 7
Output: 2
Explanation: the subarray [4,3] has the minimal length under the problem constraint.

AC代码

    public int minSubArrayLen(int s, int[] nums) {
if(nums == null || nums.length == 0)
return 0;
int ret = Integer.MAX_VALUE;
int sum = 0;
int count = 0;
for(int i = nums.length - 1; i >= 0; i--) {
sum = 0;
int j = i;
count = 0;
while(sum < s && j >= 0) {
sum += nums[j];
j--;
count++;
}
if(sum >= s)
ret = Math.min(ret, count);
}
if(ret == Integer.MAX_VALUE)
return 0;
return ret;
}

class Solution {
public int minSubArrayLen(int s, int[] nums) {
int left = 0, right = -1;
int ret = nums.length + 1;
int sum = 0;
while(left >= 0 && left < nums.length) {
if(right + 1 < nums.length && sum < s) {
right ++;
sum += nums[right];
}else {
sum -= nums[left];
left ++;
}
if(sum >= s)
ret = Math.min(ret, right - left + 1);
}

if(ret == nums.length + 1)
return 0;
return ret;
}
}

• 广告
• 抄袭
• 版权
• 政治
• 色情
• 无意义
• 其他

120