从大量数据中除去重复数据

22 篇文章 0 订阅
有道题说的是,如何从大量的数据中消除重复的数据
比如有1w个数据,怎么快速的删除重复的数据呢

有一些解法是先排序,然后逐一删除
如果采取快速排序的方式呢,复杂度是O(nlogn)
接着还有遍历一边,删除重复的数据。

如果采用hash来做,似乎可以取得更好的结果:
大概方法如下:
采用取模hash函数,
找一个hash函数了,就这么映射过去,采用链接法避免冲撞
如果A   映射后的值和B,C,D...映射的相同,采用字符串匹配,如果A!=B,C,D...,把A加入链表,若相同,删除A,继续遍历

下面偶采用了map和set来实现。速度还是非常快的,测试数据10W条。
map装载(hashed number,Set)
set装载测试的数据

代码如下,在VS2005下测试通过:
#include  < iostream >
#include 
< fstream >
#include 
< map >
#include 
< set >

using   namespace  std;



int  main()
{
    ifstream inf(
"aa.txt");
    ofstream outf(
"bb.txt");
    
if(!inf || !outf)
    
{
        cerr
<<"Can not load files"<<endl;
        exit(
0);
    }


    typedef 
set<int> collision_data;
    map
<int , collision_data *> hash_data;
    
const int Ihash=323;

    
int imod;
    
int itemp;

    map
<int , collision_data *>::iterator it;
    collision_data 
*ctemp;
    
while(inf>>itemp)
    
{
        imod
=itemp%Ihash;
        it
=hash_data.find(imod);
        
//----------if we can find the hashed data,let's check the number
        if(it!=hash_data.end())
        
{
            ctemp
=it->second;
            
//---------if can not find the number in the set,insert into the set and output to the file
            if(ctemp->count(itemp)<1)
            
{
                ctemp
->insert(itemp);
                outf
<<itemp<<endl;//--output the number
            }


        }

        
else  //we can not find the hashed data,then input it into the map
        {
            ctemp
=new collision_data;
            hash_data.insert(make_pair(imod,ctemp));
            ctemp
->insert(itemp);
            outf
<<itemp<<endl;
        }

    }

    system(
"pause");
    
return 0;
}


如果你有更好的想法,请告诉偶
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值