数据结构实验:哈希表
Time Limit: 1000MS Memory Limit: 65536KB
Problem Description
在n个数中,找出出现次数最多那个数字,并且输出出现的次数。如果有多个结果,输出数字最小的那一个。
Input
单组数据,第一行数字n(1<=n<=100000)。
接下来有n个数字,每个数字不超过100000000
Output
出现次数最多的数字和次数。
Example Input
3
1 1 2
Example Output
1 2
代码:
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#define mod 100000;
typedef struct node
{
int data;
struct node *next;
}ST;
int a[100000];
ST *h[100000];
void creat(int x)
{
ST *p;
int i;
i = x % mod;//取膜,就代表取膜结果相同的数,存到同一条链表里
p = (ST *)malloc(sizeof(ST));//申请空间
p->data = x;//把前面输入的a[i]存入其中
p->next = h[i];//这里类似与链表的插入数的操作,在链表开头多加一个结点的感觉
h[i] = p;
}
int find(int x)
{
ST *p;
int i, num = 0;
i = x % mod;//取摸找对应的链表
for(p = h[i]; p; p = p->next)
{
if(p->data == x)//找到和他一样的数,num++记下出现次数
num++;
}
return num;
}
int main()
{
int n, max, i, ma;
while(~scanf("%d", &n))
{
max = 0;
for(i = 0; i < n; i++)
{
scanf("%d", &a[i]);
creat(a[i]);//将其存入哈希表中
}
for(i = 0; i < n; i++)
{
if(max < find(a[i]) || (max == find(a[i]) && ma > a[i]))//找出现次数最多的,如果出现次数一样,取最小的
{
max = find(a[i]);//找到次数更多的,或者次数相同,去最小的,跟新max的次数
ma = a[i];//对应的数
}
}
printf("%d %d\n", ma, max);
}
return 0;
}