Minimum Size Subarray Sum

来源:互联网 发布:监控计算机的软件 编辑:程序博客网 时间:2024/05/02 00:43

题目描述

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.

题目解答

题目分析

两个指针, start end, end向后走,直到 sum 大于等于 s. 然后start向后, 直到sum 小于s. 同时更新 min值.

代码实现

public class Solution {    public int minSubArrayLen(int s, int[] nums) {        if(nums == null || nums.length == 0)            return 0;        int start = 0, end = 0;        int len = nums.length;        int sum = 0, min = Integer.MAX_VALUE;        while(start < len && end < len) {            while(sum < s && end < len) {                sum += nums[end];                end++;            }            while(sum >= s && start <= end) {                min = Math.min(min, end-start);                sum -= nums[start];                start++;            }        }        return min == Integer.MAX_VALUE ? 0 : min;    }}
0 0
原创粉丝点击