http://pat.zju.edu.cn/contests/pat-a-practise/1054
求数组中出现次数超过一半的那个数字(题目保证一定存在)。
解法一:用哈希表。这里就不给出代码了。
解法二:有一个数字出现次数超过了一半,也就是说,剩余的数字出现次数之和也没有这个数字多。 那我们可以用如下方法统计:num记录当前数字,times记录当前数字出现的次数,当新遍历到一个数字和num一样,times加1, 否则减一,当times < 0时需要更新num。
#include <iostream>
#include <cstdio>
#include <vector>
#include <string>
using namespace std;
int main()
{
int n, m, i, x;
//cin>>n>>m;
scanf("%d %d", &n, &m);
n *= m;
int num, times;
for(i = 0; i < n; i ++)
{
//cin>>x;
scanf("%d", &x);
if(i == 0)
{
num = x;
times = 1;
continue;
}
if(x == num) times ++ ;
else
{
times -- ;
if(times < 0)
{
num = x;
times = 1;
}
}
}
//cout<<num<<endl;
printf("%d\n", num);
return 0;
}