数据结构实验:哈希表
Time Limit: 1000ms Memory limit: 65536K 有疑问?点这里^_^
题目描述
在n个数中,找出出现次数最多那个数字,并且输出出现的次数。如果有多个结果,输出数字最小的那一个。
输入
单组数据,第一行数字n(1<=n<=100000)。
接下来有n个数字,每个数字不超过100000000
接下来有n个数字,每个数字不超过100000000
输出
出现次数最多的数字和次数。
示例输入
3 1 1 2
示例输出
1 2
在录入链表组时应注意:
i的取值范围为一个数字模除确定数的结果范围通常为0到某个数字;故在开区间时应当从0开始开辟数组,既在for中i应当从0开始直到你要模除的数的前一位(也就是:(i=0;i<s;i++);s为接下来进行模除时的被模除数
来源
cz
示例程序
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct nod
{
int num;
int gs;
struct nod *next;
} * dnp,np;
dnp head[1000020];
int main()
{
dnp p,q,r;
int i,x,y,n,sum=-1,sgs=-1;
for(i=0; i<100000; i++)
{
head[i]=(dnp)malloc(sizeof(np));
head[i]->next=NULL;
}
p=(dnp)malloc(sizeof(np));
q=(dnp)malloc(sizeof(np));
scanf("%d",&n);
for(i=0; i<n; i++)
{
scanf("%d",&x);
y=x%100000;
p=head[y]->next;
q=head[y];
while(p!=NULL)
{
if(p->num==x)
{
p->gs++;
if(sum<p->gs)
{
sum=p->gs;
sgs=p->num;
}
else if(sum==p->gs)
{
if(sgs>p->num)
sgs=p->num;
}
break;
}
q=p;
p=p->next;
}
if(p==NULL)
{
r=(dnp)malloc(sizeof(np));
r->num=x;
r->gs=1;
if(sum<r->gs)
{
sum=r->gs;
sgs=r->num;
}
else if(sum==r->gs)
{
if(sgs>r->num)
sgs=r->num;
}
q->next=r;
r->next=NULL;
}
}
printf("%d %d\n",sgs,sum);
return 0;
}