n个数里出现次数大于等于n/2的数

题目描述

输入n个整数,输出出现次数大于等于数组长度一半的数。

输入描述:

每个测试输入包含 n个空格分割的n个整数,n不超过100,其中有一个整数出现次数大于等于n/2。

输出描述:

输出出现次数大于等于n/2的数。
示例1

输入

复制
3 9 3 2 5 6 7 3 2 3 3 3

输出

复制
3


//原本没考虑到负数,所以刚开始用的桶排序,并大呼这题目也太简单了吧,写完提交因为真的对了,好奇搜搜别人怎么做的才知道自己没考虑负数,先贴出来正整数版本

#include<bits/stdc++.h>
using namespace std;
int main()
{
   int n,a[101]={0},j=0;
   while(cin>>n)
  {
   a[n]+=1;
   j++;
  }
   for(int i=1;i<=j;i++)
   {
       if(a[i]>=j/2)
        cout<<i<<endl;
   }
   return 0;
}

//下面用strin数组重新敲一遍。。。。。。。。。。。。。。。。。

#include<bits/stdc++.h>
using namespace std;
int main()
{
    string a;
    while(getline(cin,a))
    {
       int b[101]={0};
        int j=0;
        for(int i=a.length()-1;i>=0;)
        {
            int temp=0;
            int count=-1;
            int flag=0;
            while(a[i]!=' '&&i>=0)
            {
                if(a[i]!='-')
                {
                    count++;
                    temp+=(a[i]-48)*pow(10,count);
                }
                else
                    flag=1;
                i--;
            }
            if(flag==1)
                b[j]=temp*(-1);
                else
                    b[j]=temp;
                j++;
                i--;
            }
            for(int i=0;i<j;i++)
            {
                int count1=1,shuzi;
                for(int q=i+1;q<j;q++)
                {
                    if(b[i]==b[q])
                    {
                        count1++;
                        shuzi=b[i];
                    }
                }
                if(count1>=j/2)
                    cout<<shuzi<<endl;
            }
        }
    return 0;
}





猜你喜欢

转载自blog.csdn.net/zhangao230/article/details/80910560