209. Minimum Size Subarray Sum
Problem statement:
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.
Solution:
It looks like 53. Maximum Subarray. But they are different solutions. I solve this problem by two pointers, left and right. The return value is the min length which is greater than or equal to the target. I can control the movement of these two pointers to update the min length.
Basic idea:
- If sum >= target, left moves to the end and minus the value of left, meanwhile update the min length.
- One terminating condition is left > right, that means we already find the min length is 1 and return. Otherwise, I find until the end.
- If sum < target, right moves to the end and plus the value of right.
Since left and right move at most n steps. Time complexity is O(2 * n) ---> O(n).
class Solution { public: int minSubArrayLen(int s, vector<int>& nums) { if(nums.empty()){ return 0; } int left = 0; int right = 0; int sum = nums[left]; int len = INT_MAX; while(left <= right && left < nums.size() && right < nums.size()){ // if current sum is a solution if(sum >= s){ // update the len len = min(len, right - left + 1); // update the sum // minus first and move left towards end sum -= nums[left++]; } else { // the sum is still less than target // move right to the end and update the sum sum += nums[++right]; } } // return 0 if no answer return len == INT_MAX ? 0 : len; } };
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 深入理解 Mybatis 分库分表执行原理
· 如何打造一个高并发系统?
· .NET Core GC压缩(compact_phase)底层原理浅谈
· 现代计算机视觉入门之:什么是图片特征编码
· .NET 9 new features-C#13新的锁类型和语义
· 《HelloGitHub》第 106 期
· Spring AI + Ollama 实现 deepseek-r1 的API服务和调用
· 数据库服务器 SQL Server 版本升级公告
· 深入理解Mybatis分库分表执行原理
· 使用 Dify + LLM 构建精确任务处理应用