数据结构:哈希表解决大数据查重问题


在面试过程中,有时候会被问到,在上亿个数据中,找出第一个重复的数据,或找出所有重复出现的数据。

1. 找出第一个重复的数据

这里可直接使用STL的hashset

#include <iostream>
#include <unordered_set>
#include <unordered_map>
#include <vector>
#include <stdlib.h>
#include <time.h>
using namespace std;

int main(void)
{
	// vector中放入原始数据
	vector<int> vec;
	srand(time(NULL));
	
	for (int i = 0; i < 1000; ++i)
	{
		vec.push_back(rand() % 1000);
	}

	// 找第一个重复出现的数字
	unordered_set<int> st;
	for (auto key : vec)
	{
		auto it = st.find(key);
		if (it == st.end())
		{
			st.insert(key);
		}
		else
		{
			cout << "key: " << key << endl;
			break;
		}
	}
	return 0;
}

在这里插入图片描述

2. 找出所有重复的数据,并统计重复次数

这种问题,就可以用STL的unordered_map

#include <iostream>
#include <unordered_set>
#include <unordered_map>
#include <vector>
#include <stdlib.h>
#include <time.h>
using namespace std;

int main(void)
{
	// vector中放入原始数据
	vector<int> vec;
	srand(time(NULL));
	
	for (int i = 0; i < 1000; ++i)
	{
		vec.push_back(rand() % 1000);
	}

	// 找重复出现的数字
	unordered_map<int, int> mp;
	for (auto key : vec)
	{
		mp[key]++;
	}

	for (auto pair : mp)
	{
		if (pair.second > 1)
		{
			cout << "key: " << pair.first << "  cnt: " << pair.second << endl;
		}
	}

	return 0;
}

在这里插入图片描述

3. 找出第一个没有重复的字符

#include <iostream>
#include <unordered_set>
#include <unordered_map>
#include <vector>
#include <stdlib.h>
#include <time.h>
using namespace std;

int main(void)
{
	// 字符串,找出第一个没有重复出现的字符
	string src = "nnndddhsifbasuifbewufeabvaovbawrg";
	unordered_map<int, int> m;
	for (char ch : src)
	{
		m[ch]++;
	}
	for (char ch : src)
	{
		if (m[ch] == 1)
		{
			cout << "the first  nonrepeated character: " << ch << endl;
			return 0;
		}
	}
	cout << "all character repeated!" << endl;
	return 0;
}

在这里插入图片描述

4. 有两个文件a和b,分别放了大约一亿个IP地址(email/URL),每个地址4字节,找出两个文件重复的IP,限制内存100M

思路:分治 + 哈希表
一亿条数据,大概100M
100M * 4 * 2 = 800M

100M根本不够。

可以拆分成多个小文件,这里分成11个(素数),那每个文件平均1000W条数据,若一条数据4字节,那么用哈希表存储,把a1文件里的数据全部放入,最多只占80M大小,然后依次遍历b1内的数据,从而得到重复IP。

在这里插入图片描述

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

_索伦

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值