209. Minimum Size Subarray Sum

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.

More practice:

If you have figured out the O(n) solution, try coding another solution of which the time complexity is O(n log n).

题意:获取最短子串的长度,使其总和大于等于给定的值s
 
复制代码
 1     public int minSubArrayLen(int s, int[] nums) {
 2 //        定义两个指针left和i,分别记录子数组的左右的边界位置,每次i右移1位,就将结果累加到sum中。
 3 //        找出left到i范围内sum大于s时最小的长度(i-left+1),然后将left右移,同时在sum中去除nums[left]的值
 4         int res = Integer.MAX_VALUE, left = 0, sum = 0;
 5         for (int i = 0; i < nums.length; ++i) {
 6             sum += nums[i];
 7             while (left <= i && sum >= s) {
 8                 res = Math.min(res, i - left + 1);
 9                 sum -= nums[left++];
10             }
11         }
12         return res == Integer.MAX_VALUE ? 0 : res;        
13     }
复制代码

 

posted @   daniel456  阅读(100)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!
点击右上角即可分享
微信分享提示