数组中出现次数超过一半的数字
来源:互联网 发布:js table 高度 编辑:程序博客网 时间:2024/06/06 03:27
#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],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],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;
}
0 0
- 数组中超过出现次数超过一半的数字
- 74.数组中超过出现次数超过一半的数字
- 74 数组中超过出现次数超过一半的数字
- 【数组4】数组中出现次数超过一半的数字
- 数组4:数组中出现次数超过一半的数字
- 数组中出现次数超过一半的数字
- 找出数组中出现次数超过长度一半的数字
- 2-数组中出现次数超过一半的数字
- 数组中出现次数超过一半的数字
- 数组中出现次数超过一半的数字[算法]
- 数组中出现次数超过一半的数字
- 找出数组中出现次数超过一半的数字--百度
- 数组中出现次数超过一半的数字
- 数组中出现次数超过一半的数字
- 数组中出现次数超过一半的数字
- 寻找数组中出现次数超过一半的数字
- 面试训练数组中出现次数超过一半的数字
- 数组中出现次数超过一半的数字
- SQL: 视图和表的区别
- CF237 E 404E - Maze 1D(二分)
- 在Django 1.5 中 Django Step by Step (九)教程分页实现方法的修正
- 简单的汇编实例注释
- TWiki架设
- 数组中出现次数超过一半的数字
- 实现三年前的誓言
- 覆写JAVA中的CompareTo()方法与toString()方法的实现
- (intermediate) UVA 最短路 10968 - KuPellaKeS
- JPEG 原理详细实例分析及其在嵌入式 Linux 中的应用
- ubuntu 中安装 hadoop 记录
- Xen虚拟机修改root密码
- RequireJS - 简介
- string