- 题目描述:
-
数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。例如输入一个长度为9的数组{1,2,3,2,2,2,5,4,2}。由于数字2在数组中出现了5次,超过数组长度的一半,因此输出2。
- 输入:
-
每个测试案例包括2行:
第一行输入一个整数n(1<=n<=100000),表示数组中元素的个数。
第二行输入n个整数,表示数组中的每个元素,这n个整数的范围是[1,1000000000]。
- 输出:
-
对应每个测试案例,输出出现的次数超过数组长度的一半的数,如果没有输出-1。
- 样例输入:
-
9
-
1 2 3 2 2 2 5 4 2
- 样例输出:
-
2
先把数组num排序,如果存在出现次数 > n/2 的数X,则num[n/2]一定是X;
(这样比用hash节省了空间和不必要的计算,因为只需要计算X出现的次数就可以了。)
AC代码:
#include<stdio.h>
#include<stdlib.h>
int num[100001];
int cmp(const void *a, const void *b) {
return (*(int *)a - *(int *)b);
}
int main() {
int i, n, m;
while(scanf("%d", &n) != EOF) {
int count = 0;
for(i = 0; i < n; i++) {
scanf("%d", &num[i]);
}
qsort(num, n, sizeof(int), cmp);
int mid = num[n/2]; /*if there is the number x that occured > n/2 times, num[n/2] must be x*/
for(i = 0; i < n; i++) {
if(num[i] == mid) {
count++;
}
}
if(count > n/2) {
printf("%d\n", mid);
}
else {
printf("-1\n");
}
}
return 0;
}
/**************************************************************
Problem: 1370
User: wusuopuBUPT
Language: C
Result: Accepted
Time:70 ms
Memory:1696 kb
****************************************************************/