本文主要是介绍**Leetcode 209. Minimum Size Subarray Sum | 区间和符合条件 = k,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
https://leetcode.com/problems/minimum-size-subarray-sum/description/
O(n)可解
class Solution {
public:int minSubArrayLen(int s, vector<int>& nums) {if (nums.size()==0 || s == 0) return 0;int cur = nums[0], left = 0, right = 0;int ret = nums.size() + 1;while (right < nums.size()){if (cur >= s) {ret = min(ret, right - left + 1);cur -= nums[left];left++;} else {right ++;cur += nums[right]; }} return ret == nums.size() + 1 ? 0 : ret;}
};
另外拿这个题当二分联系了,二分长度
class Solution {
public:int minSubArrayLen(int s, vector<int>& nums) {int cur = 0, left = 0, l = 0, r = nums.size(), get = 0;for (int i = 0; i < nums.size(); i++) cur += nums[i];if (cur<s) return 0;while (l < r) {int mid ;mid =l + ((r - l )>>1);bool check = false;for (left=0; left + mid -1 < nums.size(); left++) {if (left == 0) {cur = 0;for (int i = left; i < left + mid; i++) {cur += nums[i];}} else {cur -= nums[left-1];cur += nums[left + mid -1];}if (cur >= s) {check = true;get = 1;break;} }if (check) {r = mid;} else {l = mid + 1;}}if (get) return r; else return nums.size();}
};
这个可以作为模板,注意点就是 r=mid这种写法,当长度为1的时候,必须是做端点,对应上面mid的写法。
为了防止死循环,每次代入l=2 r=3检查一次
这篇关于**Leetcode 209. Minimum Size Subarray Sum | 区间和符合条件 = k的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!