数据结构 查找 哈希表

哈希表

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

注意两点:

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

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

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

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

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

As a general rule, the  default  load factor (. 75 ) offers a good tradeoff between time and space costs. Higher values decrease the space overhead but increase the lookup cost (reflected  in  most of the operations of the HashMap  class , including  get  and put). The expected number of entries  in  the map and its load factor should be taken into account when setting its initial capacity, so  as  to minimize the number of rehash operations. If the initial capacity  is  greater than the maximum number of entries divided by the load factor, no rehash operations will ever occur. 

当LF > 0.75时,要进行rehash。

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

/**
 * @(#)Hashtable.java    1.13 03/01/23
 *
 * Copyright 2003 Sun Microsystems, Inc. All rights reserved.
 * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 
*/

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

/**
 * A generic simplified version of java.util.Hashtable.
 
*/

public   class  Hashtable  {

    ...

    
private void dble() {
        hashSize 
= hashSize << 1;
        hashMask 
= hashSize - 1;
        limit 
= limit << 1;
        Entry[] oldtable 
= table;
        table 
= new Entry[hashSize];
        
for (int i = 0; i < oldtable.length; i++{
            
for (Entry e = oldtable[i], next = null; e != null; e = next) {
                next 
= e.next;
                
int ix = e.hash & hashMask;
                e.next 
= table[ix];
                table[ix] 
= e;
            }

        }

    }


    ...
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值