双指针算法
主要内容
双指针有很多种,第一类是两个指针在不同的序列上,比如归并排序的区间合并问题,还有一类是两个指针指向同一序列的不同位置来解决一些问题。主要遇到的是第二类。
针对第二类
,一般可套用下面的模板
。双指针实质上是根据问题的某种特性
,比如单调性,来对朴素算法
进行优化
。

经典例题
A+B
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
|
#include<bits/stdc++.h> using namespace std;
void work(){ string s; getline(cin,s);
int n=s.size();
for(int i=0;i<n;i++){ int j=i; while(j<n&&s[j]!=' ') j++;
for(int k=i;k<j;k++) cout<<s[k]; cout<<endl;
i=j; } }
int main(){ work(); return 0; }
|
最长连续不重复子序列
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
|
#include<bits/stdc++.h> using namespace std;
const int N=1e5+5; int a[N]; int s[N]; int n;
void work(){ cin>>n; for(int i=0;i<n;i++) cin>>a[i];
int mx=1;
for(int i=0,j=0;i<n;i++){ s[a[i]]++; while(s[a[i]]>1){ s[a[j]]--; j++; }
mx=max(mx,i-j+1); }
cout<<mx<<endl; }
int main(){ work(); return 0; }
|