在n个数中,找出出现次数最多那个数字,并且输出出现的次数。如果有多个结果,输出数字最小的那一个(输入的数可能很大)
- #include<stdio.h>
- #include<stdlib.h>
- struct node
- {
- int time;
- int data;
- struct node *next;
- }*head[100000];//多个链表存放
- int main()
- {
- int i,maxtime=-1,maxshu=-1,n;
- int a,b,c;
- struct node *p,*r,*q;
- for(i=0; i<100000; i++)//给每个头开辟空间
- {
- head[i]=(struct node *)malloc(sizeof(struct node));
- head[i]->next=NULL;
- }
- p=(struct node *)malloc(sizeof(struct node));
- q=(struct node *)malloc(sizeof(struct node));
- scanf("%d",&n);
- while(n--)
- {
- scanf("%d",&a);
- b=a%100000;//把余数相同的放在一起容易查找也容易存数
- p=head[b]->next;
- q=head[b];
- while(p!=NULL)
- {
- if(p->data==a)//存的是原来输入的树而不是余数
- {
- p->time++;
- if(p->time>maxtime)//次数多的则取多的,同时最大数也要换
- {
- maxshu=p->data;
- maxtime=p->time;
- }
- if(p->time==maxtime&&p->data<maxshu)
- maxshu=p->data;//次数相同取值小的,次数不用换
- break;//可以不加break,但不加的话,用时会长点
- }
- q=p;
- p=p->next;
- }
- if(p==NULL)
- {
- r=(struct node *)malloc(sizeof(struct node));//要在这开空间,在上面和p,q一起的话会超时的
- r->data=a;
- r->next=q->next;//将r插入最后,也可用r->next=NULL;
- q->next=r;
- r->time=1;
- if(r->time>maxtime)
- {
- maxtime=r->time;
- maxshu=a;
- }
- if(r->time==maxtime&&r->data<maxshu)
- maxshu=a;
- }
- }
- printf("%d %d\n",maxshu,maxtime);
- return 0;
- }
本文介绍了一种使用链表实现的数据结构来高效找出一组整数中出现次数最多的数字及其出现次数的方法。通过将输入的整数按余数分组并利用链表记录每个数字的出现频率,实现了快速查找。
2289

被折叠的 条评论
为什么被折叠?



