双指针
即一个指针在数组之前,另一个指针在数组之后
两个指针的动作是不协调的(打个比方
指针a动的时候指针b就不动,反之亦然
双指针的应用有
1、快速排序
2、将数组分成两个指定的堆
3、在数组中找指定的某两个数
代码如下
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
#include <map> #include <set> #include <cmath> #include <ctime> #include <stack> #include <queue> #include <cstdio> #include <cctype> #include <bitset> #include <string> #include <vector> #include <cstring> #include <iostream> #include <algorithm> #include <functional> #define fuck(x) cout<<"["<<x<<"]"; #define FIN freopen("input.txt","r",stdin); #define FOUT freopen("output.txt","w+",stdout); //#pragma comment(linker, "/STACK:102400000,102400000") using namespace std; typedef long long LL; typedef pair<int, int> PII; const int maxn = 1e5+5; //找一对数等于指定数 int getThePair(int *a,int n,int theNum,int &left,int &right){ int start = 0 , end = n-1; while(start<end){ int sum = a[start] + a[end]; if(sum==theNum){ left=a[start]; right=a[end]; return 1; } if(sum<theNum){ start++; }else if(sum>theNum){ end--; } } return 0; } //将数组分成奇数堆和偶数队 void partiton(int *a,int n){ int i=0; int j=n-1; while(i<j){ while(i<j&&a[i]%2==1) i++; while(i<j&&a[j]%2==0) j--; if(i<j){ swap(a[i],a[j]); } } } int main(){ #ifndef ONLINE_JUDGE FIN #endif int n,start,end; int a[maxn]; while(scanf("%d",&n) !=EOF){ for(int i=0;i<n;i++){ scanf("%d",&a[i]); } for(int i = 1; i <= 16; i++){ if(getThePair(a,n,i,start,end)){ printf("the sum of %d is %d + %d ",i,start,end); }else{ printf("sorry,%d not found~~ ",i); } } partiton(a,n); for(int i=0;i<n;i++){ printf("%d ",a[i]); } printf(" "); } }