数据结构实验:哈希表
Time Limit: 1000 ms Memory Limit: 65536 KiB
Problem Description
在n个数中,找出出现次数最多那个数字,并且输出出现的次数。如果有多个结果,输出数字最小的那一个。
Input
单组数据,第一行数字n(1<=n<=100000)。
接下来有n个数字,每个数字不超过100000000
Output
出现次数最多的数字和次数。
Sample Input
3
1 1 2
Sample Output
1 2
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
struct node
{
int data;
int num;
struct node *next;
}*h[100010],*q,*t,*p;
int main()
{
int m,n;
int i,max=0,maxs=0;
for(i=0; i<100010; i++)
{
h[i]=(struct node*)malloc(sizeof(struct node)); //弄一个头结点
h[i]->next=NULL;
}
scanf("%d",&n);
for(i=0; i<n; i++)
{
scanf("%d",&m);
int w;
w=m%100010; //取余
q=h[w];
p=h[w]->next;
while(p!=NULL)
{
if(p->data==m)
{
p->num++;
if(p->num>maxs)
{
maxs=p->num;
max=p->data;
}
else if(p->num==maxs)
{
if(p->data<max)
{
max=p->data;
}
}
break; //如果有相等的直接跳出,并且下面那个if也不会执行
}
q=q->next;
p=p->next;
}
if(p==NULL)
{
t=(struct node*)malloc(sizeof(struct node)); //申请新的空间
t->next=NULL;
t->data=m;
t->num=1; //在链表后面插入新的,置为1;
q->next=t;
p=t;
if(p->num>maxs)
{
maxs=p->num;
max=p->data;
}
else if(p->num==maxs)
{
if(p->data<max)
max=p->data;
}
}
}
printf("%d %d\n",max,maxs);
return 0;
}