首页 > 其他 > 详细

leetcode [209]Minimum Size Subarray Sum

时间:2019-04-26 11:29:49      阅读:161      评论:0      收藏:0      [点我收藏+]

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: 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(n log n). 
 

题目大意:

给一个正整数数组,找出最短的连续子数组的长度,使得子数组的和大于给定和,如果不存这样的连续子数组,则返回0。

解法:

采用两个指针,遍历数组,一旦和比给定和要大时,记录长度并且调整指针,这种解法的时间复杂度是O(n)。

java:

class Solution {
    public int minSubArrayLen(int s, int[] nums) {
        int start=0,end=0;
        int tmpSum=0;
        int res=Integer.MAX_VALUE;
        while(end<nums.length){
            tmpSum+=nums[end];
            while(start<=end&&tmpSum>=s){
                res=Math.min(res,end-start+1);
                tmpSum=tmpSum-nums[start];
                start++;
            }
            end++;
        }

        return res==Integer.MAX_VALUE?0:res;
    }
}

leetcode [209]Minimum Size Subarray Sum

原文:https://www.cnblogs.com/xiaobaituyun/p/10773254.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!