Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

添加了209.长度最小的子数组中C++语言的另一种书写形式 #2875

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 38 additions & 0 deletions problems/0209.长度最小的子数组.md
Original file line number Diff line number Diff line change
Expand Up @@ -142,6 +142,44 @@ public:

不要以为for里放一个while就以为是O(n^2)啊, 主要是看每一个元素被操作的次数,每个元素在滑动窗后进来操作一次,出去操作一次,每个元素都是被操作两次,所以时间复杂度是 2 × n 也就是O(n)。

另一种可以直观地看出时间复杂度是O(n)的写法

```CPP
class Solution {
public:
int minSubArrayLen(int target, vector<int>& nums) {
int left = 0,right = 0,anw = nums[0];
// 使用左闭右闭写法
int min_len = 0x7F7F7F7F;
// int最大值的另一个版本,可以避免因为加减法导致溢出
while(left < nums.size()){
// 此处while(1)也可以通过
if(anw < target){
// 如果区间和不够大则需要扩大区间
right++;
if(right == nums.size()){
// 区间右端点超出范围,此时区间和已经不可能达到target的大小
break;
}
anw += nums[right];
}
else{
// 如果区间和足够则需要缩小区间
min_len = min(min_len, right - left + 1);
// 此时已经求出一个符合要求的区间,求出区间长度并与最小值比较
anw -= nums[left];
left++;
}
}
if(min_len == 0x7F7F7F7F){
// 若最小值没被更新
min_len = 0;
}
return min_len;
}
};
```

## 相关题目推荐

* [904.水果成篮](https://leetcode.cn/problems/fruit-into-baskets/)
Expand Down