zoukankan      html  css  js  c++  java
  • SSLZYC 奇数统计

    题目大意:
    给出N个正整数,其中只有一个数出现了奇数次,其余的数都出现偶数次。求那个出现了奇数次的数。


    思路:
    直接暴力!
    下面给出两种做法:
    (1)不保险的:桶排
    (2)保险的:快排
    这道题个人认为快拍更加保险。因为题目没有告诉你这个数字最大是多少,使用桶排有可能会爆内存。虽然这道题用快排比桶排慢,但是更加保险,不会有爆内存的可能。


    代码:

    桶排:

    #include <cstdio>
    using namespace std;
    
    int n,m,a[10001];
    
    int main()
    {
        freopen("count.in","r",stdin);
        freopen("count.out","w",stdout);
        scanf("%d",&n);
        for (int i=1;i<=n;i++)
        {
            scanf("%d",&m);
            a[m]++;
         } 
        for (int i=0;i<=10000;i++)
         if (a[i]%2==1) 
         {
            printf("%d\n",i);
            return 0;
         }
    }

    快排:

    #include <cstdio>
    #include <algorithm>
    using namespace std;
    
    int n,a[500001],x,head,sum,maxn;
    
    void sorts(int l,int r)
    {
        int i=l,j=r;
        int z=a[(i+j)/2];
        do
        {
            while (a[i]<z) i++;
            while (a[j]>z) j--;
            if (i<=j)
            {
                swap(a[i],a[j]);
                i++;
                j--;
            }
        }
        while (i<=j);
        if (i<r) sorts(i,r);
        if (j>l) sorts(l,j);
    }
    
    int main()
    {
        freopen("count.in","r",stdin);
        freopen("count.out","w",stdout);
        scanf("%d",&n);
        a[n+1]=-2147483646;
        for (int i=1;i<=n;i++)
        {
            scanf("%d",&a[i]);
        }
        sorts(1,n);
        head=a[1];
        sum=1;
        for (int i=2;i<=n+1;i++)
        {
            if (a[i]==head) sum++;
            else 
            {
                if (sum%2==1)
                {
                    printf("%d\n",a[i-1]);
                    return 0;
                }
                head=a[i];
                sum=1;
            }
        }
    }
  • 相关阅读:
    关于如何使用Microsoft Word发博客
    TEST
    信息安全系统设计基础第三周学习总结
    信息安全系统设计基础第一周学习总结
    Java程序设计实验 实验五
    实验三 敏捷开发与XP实践 实验报告
    git 连接github的配置
    nginx是什么,如何使用
    spring-boot 全面认知
    删除指定目录文件夹下的文件
  • 原文地址:https://www.cnblogs.com/hello-tomorrow/p/9313117.html
Copyright © 2011-2022 走看看