ssl1063-统计数字【哈希表】

本文介绍了一道关于哈希统计的应用题目,通过哈希表实现对大量整数的频率统计,并提供了完整的C++代码实现及解析。适用于初学者理解和实践哈希表的基本操作。

前言

先做赌徒的,结果发现这道题太TM简单了,然后就先做这道题了。


正题

给出n(1<=n<=200000)个数字,每个数字不超过1500000000。求每个数字出现的次数


输入输出(建议无视)

Input

  输入包含n+1行;
  第一行是整数n,表示自然数的个数;
  第2~n+1每行一个自然数。

Output

  输出包含m行(m为n个自然数中不相同数的个数),按照自然数从小到大的顺序输出。每行输出两个整数,分别是自然数和该数出现的次数,其间用一个空格隔开。

Sample Input

8
2
4
2
4
5
100
2
100

Sample Output

2 3
4 2
5 1
100 2


解题思路

这只是哈希的练习题,不代表哈希是最优解,反正也能过对吧(⊙v⊙)。用哈希统计


代码

#include<cstdio>
#include<algorithm>
using namespace std;
const int maxn=299993;
struct hashs{
    int c,num;
};
hashs hash[maxn];
int n,x;
int hashmath(int x)//哈希函数
{
    return x%maxn;
}
int locate(int x)//寻找位置
{
    int i=0,w=hashmath(x);
    while (i<maxn && hash[(w+i)%maxn].c!=0 && hash[(w+i)%maxn].c!=x)
      i++;
    return (w+i)%maxn;
}
void ins(int x)//插入元素
{
    int w=locate(x);
    hash[w].c=x;
    hash[w].num++;//统计次数
}
bool find(int x)//查找
{
    int w=locate(x);
    if (hash[w].c==x) return true;
    else return false;
}
bool cmp(hashs x,hashs y)//排序
{
    if (x.num==0 || y.num==0) return x.num>y.num;
    return x.c<y.c;
}
int main()
{
    scanf("%d",&n);
    for (int i=1;i<=n;i++)
    {
        scanf("%d",&x);
        ins(x);//加入
    }
    sort(hash,hash+maxn-1,cmp);//排序
    int i=0;
    while (hash[i].num!=0)
    {
        printf("%d %d\n",hash[i].c,hash[i].num);
        i++;//输出
    }
}

转载于:https://www.cnblogs.com/sslwyc/p/9218582.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值