数组中出现次数超过一半的数字
2014-03-20 20:23
127 查看
#include<iostream>
#include<algorithm>
#include<stdio.h>
using namespace std;
#define N 100005
int findMoreHalf(int a[],int n)
{
int i;
int num,count;
for(i=0;i<n;i++)
{
if(0==i)
{
num=a[i];
count=1;
}else
{
if(num==a[i])
count++;
else
count--;
if(count==0)
{
num=a[i];
count=1;
}
}
}
count=0;
for(i=0;i<n;i++)
if(num==a[i])
count++;
if(count>n/2)
return num;
return -1;
}
int findMoreHalfbySort(int a[],int n)
{
sort(a,a+n);
int temp=a[n/2];
int count=0;
for(int i=0;i<n;i++)
if(a[i]==temp)
count++;
if(count>n/2)
return temp;
return -1;
}
int main(int argc,char *argv[])
{
freopen("input.txt","r",stdin);
int a
,n,i;
while(scanf("%d",&n)!=EOF&&n)
{
for(i=0;i<n;i++)
scanf("%d",&a[i]);
int res=findMoreHalfbySort(a,n);
printf("%d\n",res);
}
return 0;
}
#include<algorithm>
#include<stdio.h>
using namespace std;
#define N 100005
int findMoreHalf(int a[],int n)
{
int i;
int num,count;
for(i=0;i<n;i++)
{
if(0==i)
{
num=a[i];
count=1;
}else
{
if(num==a[i])
count++;
else
count--;
if(count==0)
{
num=a[i];
count=1;
}
}
}
count=0;
for(i=0;i<n;i++)
if(num==a[i])
count++;
if(count>n/2)
return num;
return -1;
}
int findMoreHalfbySort(int a[],int n)
{
sort(a,a+n);
int temp=a[n/2];
int count=0;
for(int i=0;i<n;i++)
if(a[i]==temp)
count++;
if(count>n/2)
return temp;
return -1;
}
int main(int argc,char *argv[])
{
freopen("input.txt","r",stdin);
int a
,n,i;
while(scanf("%d",&n)!=EOF&&n)
{
for(i=0;i<n;i++)
scanf("%d",&a[i]);
int res=findMoreHalfbySort(a,n);
printf("%d\n",res);
}
return 0;
}
相关文章推荐
- 剑指offer(二十四)之数组中出现次数超过一半的数字
- 【剑指Offer学习】【面试题29 :数组中出现次数超过一半的数字】
- [Jobdu] 题目1370:数组中出现次数超过一半的数字
- 0057 找出数组中出现次数超过一半的数字
- 剑指Offer--029-数组中出现次数超过一半的数字
- 程序员面试题精选100题(47)-数组中出现次数超过一半的数字
- 关于数组的问题(连续子数组的最大和、数组中出现次数超过一半的数字、调整数组顺序使奇数位于偶数之前)
- 寻找数组中出现次数超过一半的数字
- [九度][何海涛] 数组中出现次数超过一半的数字
- 剑指offer——数组中出现次数超过一半的数字(不错,2 ways)
- 数组中出现次数超过一半的数字
- 剑指offer 数组中出现次数超过一半的数字
- 剑指Offer:数组中出现次数超过一半的数字
- 剑指offer—数组中出现次数超过一半的数字
- (剑指Offer)面试题29:数组中出现次数超过一半的数字
- 数组中出现次数超过一半的数字
- 剑指Offer:数组中出现次数超过一半的数字
- 数组中超过出现次数一半的数字 【微软面试100题 第七十四题】
- 数组中出现次数超过一半的数字
- 剑指offer题解 数组中出现次数超过一半的数字