zoukankan      html  css  js  c++  java
  • 双指针的一些应用

    双指针

    即一个指针在数组之前,另一个指针在数组之后

    两个指针的动作是不协调的(打个比方

    指针a动的时候指针b就不动,反之亦然

    双指针的应用有

    1、快速排序

    2、将数组分成两个指定的堆

    3、在数组中找指定的某两个数

    代码如下

    #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("
    ");
      }
    }
    View Code

    每一个不曾刷题的日子 都是对生命的辜负 从弱小到强大,需要一段时间的沉淀,就是现在了 ~buerdepepeqi
  • 相关阅读:
    java Math类方法使用
    线性逻辑回归与非线性逻辑回归pytorch+sklearn
    Java学习方向
    ubuntu16.04安装Anaconda+Pycharm+Pytorch
    迁移学习resnet
    简单的CNN图像分类datasets.MNIST/FashionMNIST
    pytorch学习2
    tools/build.c
    zBoot/Makefile
    tools/version.c
  • 原文地址:https://www.cnblogs.com/buerdepepeqi/p/9396021.html
Copyright © 2011-2022 走看看