SDUT 1480 哈希,找次数最多且数最小的

本文介绍了一种使用链表实现的数据结构来高效找出一组整数中出现次数最多的数字及其出现次数的方法。通过将输入的整数按余数分组并利用链表记录每个数字的出现频率,实现了快速查找。
 在n个数中,找出出现次数最多那个数字,并且输出出现的次数。如果有多个结果,输出数字最小的那一个(输入的数可能很大)
  1. #include<stdio.h>  
  2. #include<stdlib.h>  
  3. struct node  
  4. {  
  5.     int time;  
  6.     int data;  
  7.     struct node *next;  
  8. }*head[100000];//多个链表存放  
  9. int main()  
  10. {  
  11.     int i,maxtime=-1,maxshu=-1,n;  
  12.     int a,b,c;  
  13.     struct node *p,*r,*q;  
  14.     for(i=0; i<100000; i++)//给每个头开辟空间  
  15.     {  
  16.         head[i]=(struct node *)malloc(sizeof(struct node));  
  17.         head[i]->next=NULL;  
  18.     }  
  19.     p=(struct node *)malloc(sizeof(struct node));  
  20.     q=(struct node *)malloc(sizeof(struct node));  
  21.     scanf("%d",&n);  
  22.     while(n--)  
  23.     {  
  24.         scanf("%d",&a);  
  25.         b=a%100000;//把余数相同的放在一起容易查找也容易存数  
  26.         p=head[b]->next;  
  27.         q=head[b];  
  28.         while(p!=NULL)  
  29.         {  
  30.             if(p->data==a)//存的是原来输入的树而不是余数  
  31.             {  
  32.                 p->time++;  
  33.                 if(p->time>maxtime)//次数多的则取多的,同时最大数也要换  
  34.                 {  
  35.                     maxshu=p->data;  
  36.                     maxtime=p->time;  
  37.                 }  
  38.                 if(p->time==maxtime&&p->data<maxshu)  
  39.                     maxshu=p->data;//次数相同取值小的,次数不用换  
  40.                 break;//可以不加break,但不加的话,用时会长点  
  41.             }  
  42.             q=p;  
  43.             p=p->next;  
  44.         }  
  45.         if(p==NULL)  
  46.         {  
  47.             r=(struct node *)malloc(sizeof(struct node));//要在这开空间,在上面和p,q一起的话会超时的  
  48.             r->data=a;  
  49.             r->next=q->next;//将r插入最后,也可用r->next=NULL;  
  50.             q->next=r;  
  51.             r->time=1;  
  52.             if(r->time>maxtime)  
  53.             {  
  54.                 maxtime=r->time;  
  55.                 maxshu=a;  
  56.             }  
  57.             if(r->time==maxtime&&r->data<maxshu)  
  58.                 maxshu=a;  
  59.         }  
  60.     }  
  61.     printf("%d %d\n",maxshu,maxtime);  
  62.     return 0;  
  63. }   
  64.   
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值