本文主要是介绍209. Minimum Size Subarray Sum(Leetcode每日一题-2020.06.28),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
Problem
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.
Solution
滑动窗口
class Solution {
public:int minSubArrayLen(int s, vector<int>& nums) {int ans = INT_MAX;int sum = 0; //窗口间的和int l = 0; //滑窗的左边框int r = 0; //滑窗的右边框while( l<= r && r < nums.size()) //滑窗的右边框不能超出界限{if(sum + nums[r] < s) //若滑窗之间的和小于s,右边框右移,sum增大{sum += nums[r];++r;}else //若滑窗之间的和大于等于s,左边框右移,sum减小{ans = min(ans,r-l+1);sum = sum - nums[l];++ l;}}return ans == INT_MAX? 0:ans;}
};
这篇关于209. Minimum Size Subarray Sum(Leetcode每日一题-2020.06.28)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!