209. Minimum Size Subarray Sum

来源:互联网 发布:好看的港剧推荐知乎 编辑:程序博客网 时间:2024/06/13 15:04

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.

click to show more practice.

Credits:
Special thanks to @Freezen for adding this problem and creating all test cases.

Subscribe to see which companies asked this question.

public class Solution {    public int minSubArrayLen(int s, int[] nums) {        int re = Integer.MAX_VALUE;int sum = 0;int start = 0;int end = 0;while (end < nums.length) {sum += nums[end];if (sum < s) {end++;continue;}while (start <= end) {if (sum - nums[start] >= s)sum -= nums[start++];elsebreak;}re = Math.min(re, end - start + 1);end++;}return re == Integer.MAX_VALUE ? 0 : re;    }}


0 0
原创粉丝点击