LeetCode-209. Minimum Size Subarray Sum

网友投稿 239 2022-08-29

LeetCode-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.

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.

题解:

滑动窗口。

class Solution {public: int minSubArrayLen(int s, vector& nums) { int n = nums.size(); if (n == 0) { return 0; } int l = 0, r = 0, sum = 0, res = INT_MAX; while (r < n) { sum += nums[r]; while (sum >= s) { res = min(res, r - l + 1); sum -= nums[l]; l++; } r++; } if (res == INT_MAX) { return 0; } return res; }};

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:如何做好国内企业的网络营销?(中小企业如何运用网络营销)
下一篇:LeetCode-219. Contains Duplicate II
相关文章

 发表评论

暂时没有评论,来抢沙发吧~