PAT 1054. The Dominant Color (20)

来源:互联网 发布:炉石传说激活码淘宝买 编辑:程序博客网 时间:2024/05/21 14:46

方法一:排序,然后计算最多的且超过总数的1/2; 会超时
方法二:map的使用;
方法三:因为我们所要求的数出现的次数超过总数目一半,所以将不相同的数两两抵消,那么最终剩下的便是我们要求的数。当然这不是我能想到的。
方法二代码:

#include<iostream>#include<cstdio>#include<cstring>#include<algorithm>#include<map>using namespace std;int main(){  int n,m;  while(cin>>n>>m)  {    map <int,int> t;    int x[480000];    for(int i = 0; i < n*m; i++)    {      cin>>x[i];      t[x[i]]++;    }    int max = 0,temp;    for(int i = 0; i < n*m; i++)      if(t[x[i]] > max && t[x[i]] > (m * n)/2)      {        max = t[x[i]];        temp = x[i];      }    cout<<temp<<endl;  }  return 0;}

方法三代码:

#include<iostream>#include<cstdio>using namespace std;int main(){  int n,m;  while(scanf("%d%d",&n,&m)!=EOF)  {    int number = 0,x;    for(int i = 0; i < n*m; i++)      {        int t;        cin>>t;        if(number == 0)        {          x = t;          number++;        }else        {          if(x == t)            number++;          else            number--;        }       }    cout<<x<<endl;  }  return 0;}
0 0