双指针
- 对于一个序列,用两个指针维护一段区间;
- 对于两个序列,维护某种次序,比如归并排序中合并两个有序序列的操作;
for(int i = 0, j = 0; j < n; j++)
{
//当前维护的区间不满足条件,i向前移动到满足条件
while(i < j && check(i, j)) i++;
//具体逻辑
}
最长连续不重复子序列
题目链接:https://www.acwing.com/problem/content/801/
//维护一个区间
#include<iostream>
#include<unordered_map>
const int N = 100100;
int arr[N];
using namespace std;
int main()
{
int n;
cin >> n;
for(int i = 0; i < n; i++)
cin >> arr[i];
unordered_map<int, int> hashmap;
int cnt = 0;
for(int i = 0, j = 0; j < n; j++)
{
hashmap[arr[j]]++;
while(i < j && hashmap[arr[j]] > 1)
{
hashmap[arr[i]]--;
i++;
}
cnt = max(cnt, j - i + 1);
}
cout << cnt << endl;
return 0;
}
数组元素的目标和
题目链接:https://www.acwing.com/problem/content/802/
#include <iostream>
using namespace std;
const int N = 100010;
int a[N], b[N];
int main()
{
int n, m, x;
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(j >= 0 && a[i] + b[j] == x)
cout << i << " " << j << endl;
}
return 0;
}