您的位置:首页 > 其它

数组中出现次数超过一半的数字

2014-09-05 11:59 197 查看
题目描述:
数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。例如输入一个长度为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


#include <stdio.h>
void main()
{
int n;
while(scanf("%d",&n)!=EOF)
{
int array[100000];
for (int i=0; i< n; i++)
{
scanf("%d",&array[i]);
}
int result = array[0];
int times = 1;
i = 0;
while(i < n)
{
if (times == 0)
{
result = array[i];
times = 1;
}
if (result == array[i])
times++;
else
times--;
i++;
}
int count =0;
for (int j=0; j < n; j++)
{
if(array[j]  == result)
count++;
}
if (2*count > n)
printf("%d\n",result);
else
printf("-1\n");
}
}


another methord

#include <stdio.h>

int partition(int array[], int start, int end)
{
int key = array[start];
while(start < end)
{
while(start<end && array[end]>=key) end--;
if (start<end)
{
array[start] = array[end];
start++;
}
else
{
break;
}

while(start <end && array[start] < key) start++;
if (start < end)
{
array[end] = array[start];
end--;
}
}
array[start] = key;
return start;
}

int checkMoreHalf(int array[],int lenght,int number)
{
int total = 0;
for (int i=0; i<lenght; i++)
{
if (array[i] == number)
total++;
}
if (2*total > lenght)
{
return 1;
}
return -1;
}

void MoreThanHalfNum(int array[], int length)
{
int middle = length >> 1;
int start  = 0;
int end    = length -1;
int index = partition(array,start,end);
while(index != middle)
{
if (index > middle)
{
end = index -1;
}
else
{
start = index+1;
}
index = partition(array,start,end);
}
if (checkMoreHalf(array,length,array[index]) == 1)
{
printf("%d\n",array[index]);
}
else
{
printf("-1\n");
}
}

void main()
{
int n;
while(scanf("%d",&n)!=EOF)
{
int array[100000];
for (int i=0; i< n; i++)
{
scanf("%d",&array[i]);
}
MoreThanHalfNum(array,n);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: