双指针模板
for (int i = 0, j = 0; i < n; i ++ )
{
while (j < i && check(i, j)) j ++ ;
// 具体问题的逻辑
}
AcWing 799. 最长连续不重复子序列
#include <iostream>
using namespace std;
const int N = 100010;
int n;
int a[N], s[N];
int main()
{
cin >> n;
for (int i = 0; i < n; i ++) cin >> a[i];
int res;
for (int i = 0, j = 0; i < n; i ++)
{
s[a[i]] ++; //记录i指针经过的数
while (s[a[i]] > 1) //当此时i指针指向的数出现次数大于1,即有重复
{
s[a[j]] --;
j ++; //弹出j指向的数并往前走一步
}
res = max(res, i - j + 2);
}
cout << res << endl;
return 0;
}
AcWing 800. 数组元素的目标和
#include <iostream>
using namespace std;
const int N = 100010;
int n, m, x;
int a[N], b[N];
int main()
{
cin >> n >> m >> x;
for (int i = 0; i < n; i ++) cin >> a[i];
for (int i = 0; i < m; i ++) cin >> b[i];
for (int i = 0, j = m - 1; i < n; i ++)
{
while (j >= 0 && a[i] + b[j] > x) j --;
if (a[i] + b[j] == x){
cout << i << " " << j;
}
}
return 0;
}
AcWing 2816. 判断子序列
#include <iostream>
using namespace std;
const int N = 100010;
int a[N], b[N];
int main()
{
int n, m;
cin >> n >> m;
for (int i = 0; i < n; i ++) cin >> a[i];
for (int i = 0; i < m; i ++) cin >> b[i];
int i = 0, j = 0;
while (i < n && j < m)
{
if (a[i] == b[j]) i ++; //当匹配时i往前
j ++; //无论匹配与否j都往前
}
if (i == n) puts("Yes");
else puts("No");
return 0;
}