
参考链接: https://leetcode-cn.com/problems/he-wei-sde-lian-xu-zheng-shu-xu-lie-lcof/solution/shi-yao-shi-hua-dong-chuang-kou-yi-ji-ru-he-yong-h/
滑动窗口
class
Solution {
public:
vector
<
vector
<
int
>>
findContinuousSequence(
int
target) {
//滑动窗口,L为左边界,R为右边界[L,R]
//L、R just swipe right,
vector
<
vector
<
int
>>
res;
//The meaning of the question can be seen from greater than or equal to1开始
int
L
=
1,
R
=
1;
int
sum
=
L;
//Because it is a continuous sequence of positive numbers,L最多到target/2 ,Because it contains at least two numbers,超过target/2 ,must be greater than target
while(
L
<=
target
/
2)
{
if(
sum
==
target)
//L往右滑动
{
vector
<
int
>
tmp;
for(
int
i
=
L;
i
<=
R;
i
++)
tmp.
push_back(
i);
res.
push_back(
tmp);
//Maintenance is also required after the value is found
sum
-=
L;
L
++;
}
else
if(
sum
<
target)
//R往右滑动,
{
R
++;
sum
+=
R;
}
else
if(
sum
>
target)
//L往右滑动,
{
sum
-=
L;
L
++;
}
}
return
res;
}
};
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
- 15.
- 16.
- 17.
- 18.
- 19.
- 20.
- 21.
- 22.
- 23.
- 24.
- 25.
- 26.
- 27.
- 28.
- 29.
- 30.
- 31.
- 32.
- 33.
- 34.
- 35.
- 36.
- 37.
- 38.
- 39.
- 40.
- 41.
- 42.
滑动窗口+双端队列
class
Solution {
public:
vector
<
vector
<
int
>>
findContinuousSequence(
int
target) {
//滑动窗口,L为左边界,R为右边界[L,R]
//L、R just swipe right,
vector
<
vector
<
int
>>
res;
//The deque maintains a sliding window at this point
deque
<
int
>
record;
//The meaning of the question can be seen from greater than or equal to1开始
int
L
=
1,
R
=
1;
int
sum
=
L;
record.
push_back(
L);
//Because it is a continuous sequence of positive numbers,L最多到target/2 ,Because it contains at least two numbers,超过target/2 ,must be greater than target
while(
L
<=
target
/
2)
{
if(
sum
==
target)
//L往右滑动
{
vector
<
int
>
tmp(
record.
begin(),
record.
end());
res.
push_back(
tmp);
//Maintenance is also required after the value is found
sum
-=
L;
L
++;
record.
pop_front();
}
else
if(
sum
<
target)
//R往右滑动,
{
R
++;
record.
push_back(
R);
sum
+=
R;
}
else
if(
sum
>
target)
//L往右滑动,
{
sum
-=
L;
record.
pop_front();
L
++;
}
}
return
res;
}
};
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
- 15.
- 16.
- 17.
- 18.
- 19.
- 20.
- 21.
- 22.
- 23.
- 24.
- 25.
- 26.
- 27.
- 28.
- 29.
- 30.
- 31.
- 32.
- 33.
- 34.
- 35.
- 36.
- 37.
- 38.
- 39.
- 40.
- 41.
- 42.
- 43.
- 44.
- 45.
- 46.
- 47.
原网站版权声明
本文为[51CTO]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/223/202208111033408758.html