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.
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 }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!