intminSubArrayLen(int target, vector<int> &nums){ int left = 0; int right = 0; int len = nums.size(); if (nums.size() == 1) { return nums[0] == target ? 1 : 0; } int sum = 0; int ret = len; while (right < len) { sum = sum + nums[right]; while (sum >= target) { //窗口内的总和符合条件,则左边收缩 ret = min(ret, right - left + 1); sum = sum - nums[left]; left++; } right++; } return ret==INT_MAX?0:ret; }
inttotalFruit(vector<int> &tree){ int res = 0; // 水果编号到数量的映射 unordered_map<int, int> veg2cnt; int n = tree.size(); // 窗口左边界 int l = 0; // 窗口右边界 for (int i = 0; i < n; ++i) { ++veg2cnt[tree[i]]; // 一旦发现超过大小,则不断收缩窗口 while (veg2cnt.size() > 2) { int currTree = tree[l]; --veg2cnt[currTree]; if (veg2cnt[currTree] == 0) { veg2cnt.erase(currTree); } ++l; } // 记录最大的窗口大小 res = max(res, i - l + 1); } return res; }