PAT 1054. The Dominant Color (20)

方法一:排序,然后计算最多的且超过总数的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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值