zoukankan      html  css  js  c++  java
  • 13:整数去重(1.9)

    分析:

    方法1:先使用数组a记录,然后使用双重循环逐个比较,把不重复的数值记录到b中。时间复杂度O(n^2)(n=10000)超时;

    方法2:先使用数组a记录,然后对数组进行排序。再扫描一遍a,将不重复的数值记录在b数组.

     STL里面有个sort函数,sort 可以对给定区间所有元素进行排序,默认的排序方式是升序。
    但使用这个函数,需要包含头文件<algorithm>和using namespace std;
     使用方法举例:
    int a[1000],要对从a[0]到a[49]的元素进行排序,只要写sort(a,a+50)就行了。

     (    sort函数可以传两个参数或三个参数。第一个参数是要排序的区间首地址,第二个参数是区间的尾地址的下一地址。)

    #include<cstdio>
    #include<cstring>
    #include<algorithm>
    using namespace std;
    int a[21000],b[21000];
    int main(){
        int x,y,n,maxn=-1,num=1,t=0;
        scanf("%d",&n);
        for(int i=0;i<=n-1;i++)    scanf("%d",&a[i]);
        sort(a,a+n);
        b[0]=a[0];
        for(int i=1;i<n;i++)    
            if (a[i]==a[i-1]);
            else {
                t++;b[t]=a[i];
            }
        for(int i=0;i<=t-1;i++) printf("%d ",b[i]);
        printf("%d
    ",b[t]);            
        return 0;
    }
    View Code

    方法3:可以不排序吗?

    v先使用数组a记录,然后使用双重循环逐个比较,把不重复的数值记录到b中。时间复杂度O(n^2)(n=10000)超时;
     或者
    v使用标记数组f,如果数值x,出现则f[x]=1.
    v边读入边处理,使用b数组记录没有重复出现的数值。
    v     读入x,如果f[x]!=1,则b[t]=x
    vt为当前读入的数值中,不同的数值个数即b数组的下标。
    v
     
    #include<cstdio>
    int f[21000]={0},b[21000];
    int main(){
        int n;
        scanf("%d",&n);
        int x,t=0;
        for(int i=1;i<=n;i++)   { 
            scanf("%d",&x);
            if (!f[x]){//判断x是否出现过,没出现过则记录同时存储 
                f[x]=1;//记录x出现过 
                t++;//b数组的下标 
                b[t]=x;
            }
        }
        for(int i=1;i<=t-1;i++) printf("%d ",b[i]);
        printf("%d
    ",b[t]);            
        return 0;
    }
    View Code

    思考:不使用数组可以吗?

    //边读入边处理,用c数组记录每个数x是否出现过,如果第一次出现直接输出llh版本
    #include<cstdio>
    #include<iostream>
    using namespace std;
    int c[20005];
    int main()
    {
        int n,i,x;
        cin>>n;
        for(i=0;i<n;i++)
        {
            cin>>x;
            if(c[x]==0)//如果x第一次出现直接输出,同时c[x]标志1
            {
                cout<<x<<' ';
                c[x]=1;
            }
        }
        return 0;
    }
    View Code
  • 相关阅读:
    new操作符
    delete和delete[] 的区别
    oracle查看编码以及修改编码
    C++的类型转换符:static_cast、dynamic_cast、reinterpret_cast和const_cast
    error:/usr/bin/ld:skipping incompatible ./libxxxx.so when searching for lxxxx
    shell环境变量以及set,env,export的区别
    malloc/free和new/delete的区别
    form表单提交回调函数
    jQuery ajax 跨域请求
    开博咯
  • 原文地址:https://www.cnblogs.com/ssfzmfy/p/5198955.html
Copyright © 2011-2022 走看看