星空网 > 软件开发 > Java

[LeetCode] Minimum Size Subarray Sum

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.

     这道题主要还是先要把题目的要求弄清楚。首先题目中所说的if there is not one, return 0 instead。怎样才算是没有呢?

     这里意思是如果我们算出来的min length和array本身的长度一样,那么我们就应该return 0。

     这里比较容易想到的是用two pointer来计算。一个pointer用来计算sum,和另一个pointer紧随其后,用来判断长度。

     代码如下。~

public class Solution {  public int minSubArrayLen(int s, int[] nums) {    //two pointer     //one from start;one follows    int start = 0;     int end = 0;          int sum = 0;     int min = nums.length;          while(start<nums.length && end<nums.length) {       while(sum<s && end<nums.length) {         sum=sum+nums[end];        end++;      }       while(sum>=s && start<=end) {         min = Math.min(min, end-start);         sum =sum-nums[start];        start++;      }     }     if(min==nums.length){      return 0;    }    return min;  }}

 




原标题:[LeetCode] Minimum Size Subarray Sum

关键词:array

*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们: admin#shaoqun.com (#换成@)。

Bing广告代理开户多少钱?Bing广告如何开户?:https://www.kjdsnews.com/a/1452251.html
直播回顾:你想要的微软广告投放实操指南都在这里~:https://www.kjdsnews.com/a/1452252.html
俄罗斯OZON适合新手吗?有哪些坑需要避开?:https://www.kjdsnews.com/a/1452253.html
lazada为什么要持续提升好评?怎么提升?:https://www.kjdsnews.com/a/1452254.html
被亚马逊限制留评,怎么用自养号破解。:https://www.kjdsnews.com/a/1452255.html
解析 | 日本JCT简易申报&标准申报,选择攻略~:https://www.kjdsnews.com/a/1452256.html
北京代理注册美国公司:https://www.xlkjsw.com/news/45731.html
品牌的注册美国公司哪家好:https://www.xlkjsw.com/news/45732.html
相关文章
我的浏览记录
最新相关资讯
海外公司注册 | 跨境电商服务平台 | 深圳旅行社 | 东南亚物流