题目链接
代码如下:
#include <iostream>
#include <cstdio>
#include <cmath>
#include <set>
#include <map>
#include <vector>
#include <string>
#include <string.h>
#include <cstdlib>
#include <queue>
#include <algorithm>
#include <cctype>
#include <sstream>
#include <cstring>
#define INF 0x3f3f3f3f// memset 无穷大时可用;
#define Maxn 50005
#define maxsize 100010
using namespace std;
int majorityNumber(int *nums,int n);
int a[maxsize];
int main(int argc, char const *argv[])
{
int n;
while(scanf("%d",&n) != EOF){
for (int i = 0; i < n; ++i)
{
scanf("%d",&a[i]);
}
printf("%d\n",majorityNumber(a,n));
}
}
int majorityNumber(int *nums,int n) {
// write your code here
if (n == 0) {
return -1;
}
int count = 0;
int major = nums[0];
for (int i = 0; i < n; i++) {
if (major == nums[i]) {
count++;
} else {
count--;
}
if (count == 0) {
major = nums[i];
count++;
}
}
count = 0;
for (int i = 0; i < n; i++) {
if (major == nums[i]) {
count++;
}
}
if (count > n / 2) {
return major;
}
return -1;
}
OVER!