数据结构 查找 哈希表

本文探讨了哈希表的基本原理及其在Java中的实现细节,包括查找与插入操作的时间复杂度为O(1),如何构造有效的哈希函数,以及解决冲突的方法如链地址法,并详细介绍了Java中HashMap的装载因子及扩容机制。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

哈希表

查找、插入均为O(1)。

注意两点:

(1)对于静态集,可以构造没有冲突的hash函数;对于动态集合(可以插入、删除),则很难。

(2)尽量找到一个好的hash函数,例如:md5等。

(3)在产生collsion之后,要解决冲突,比如链地址法(拉链,插入时插在表头)。

(4)装载因子(load factor):

a. 在Java中的HashMap中是这样写的:

Asageneralrule,the default loadfactor(. 75 )offersagoodtradeoffbetweentimeandspacecosts.Highervaluesdecreasethespaceoverheadbutincreasethelookupcost(reflected in mostoftheoperationsoftheHashMap class ,including get andput).Theexpectednumberofentries in themapanditsloadfactorshouldbetakenintoaccountwhensettingitsinitialcapacity,so as tominimizethenumberofrehashoperations.Iftheinitialcapacity is greaterthanthemaximumnumberofentriesdividedbytheloadfactor,norehashoperationswilleveroccur.

当LF > 0.75时,要进行rehash。

b. 在Java的编译器GJC1.4中,当LF > 2/3时,进行dble,代码如下:

/***/ /**
*@(#)Hashtable.java1.1303/01/23
*
*Copyright2003SunMicrosystems,Inc.Allrightsreserved.
*SUNPROPRIETARY/CONFIDENTIAL.Useissubjecttolicenseterms.
*/

package com.sun.tools.javac.v8.util;

/***/ /**
*Agenericsimplifiedversionofjava.util.Hashtable.
*/

public class Hashtable ... {

...

privatevoiddble()...{
hashSize
=hashSize<<1;
hashMask
=hashSize-1;
limit
=limit<<1;
Entry[]oldtable
=table;
table
=newEntry[hashSize];
for(inti=0;i<oldtable.length;i++)...{
for(Entrye=oldtable[i],next=null;e!=null;e=next)...{
next
=e.next;
intix=e.hash&hashMask;
e.next
=table[ix];
table[ix]
=e;
}

}

}


...
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值