题目描述:
解题思路:
采用双指针的快慢指针。
图解
可以采用前缀和,但会相较麻烦。
题解:
#include<bits/stdc++.h>
using namespace std;
const int N = 1e5 + 9;
int a[N];// 因为是连续区间(连续区间:从数轴某一点开始,差值相等的区间)
int main()
{
ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);
int n, s;cin >> n >> s;
for(int i = 1; i <= n; i++)cin >> a[i];
int sum = 0;
int ans = n + 1;
int j = 0; //以上三个初始化可以在for的int内
for(int i = 1; i <= n; i++)//i为左指针
{
while(i > j || (j + 1 <= n && sum <= s))sum += a[++j];
//j为右指针。while条件分两种情况:
//1.i>j表示区间不合法时。2.j+1<=n表示可以继续加,sum<=s。
if(sum >= s)ans = min(ans, j - i + 1);//min是取最小区间(每一次循环i,j都有可能改变)
sum -= a[i];
}
cout << (ans > n ? 0 : ans);//使用三目代替if使代码简洁。当ans>n时,代表区间不存在
return 0;
}