Leetcode刷题笔记——数据结构(哈希表)

设计哈希表

原题:
在这里插入图片描述
思路: 采用双端链表作为哈希表的基础数据结构,来实现哈希表的增删查询。关键点有两个:

  1. 一个是哈希函数的确定,这里考虑质数,最大程度地避免哈希冲突。确定好哈希函数之后,后续增删查的函数,便是做完哈希之后再进行。
  2. 确定一个基础地数据结构。这里选择双向链表。需要注意,在进行增加操作的时候,需要查询增加的元素是否存在,因为哈希表不存储重复值。

上代码:

class MyHashSet {
    private Bucket[] bucketArray;
    private int keyrange;

    /** Initialize your data structure here. */
    public MyHashSet() {
        this.keyrange=769;
        this.bucketArray=new Bucket[this.keyrange];
        for(int i=0;i<this.keyrange;i++){
            this.bucketArray[i]=new Bucket();
        }

    }
    protected int _hash(int key){
        return (key%this.keyrange);
    }
    public void add(int key) {
        int bucketindex=this._hash(key);
        this.bucketArray[bucketindex].insert(key);

    }
    
    public void remove(int key) {
        int bucketindex=this._hash(key);
        this.bucketArray[bucketindex].delete(key);

    }
    
    /** Returns true if this set contains the specified element */
    public boolean contains(int key) {
        int bucketindex=this._hash(key);
        return this.bucketArray[bucketindex].exist(key);
    }
}
class Bucket{
    private LinkedList<Integer> con; 
    public Bucket(){
        con=new LinkedList<Integer>();
    }
    public void insert(Integer key){
        int index=this.con.indexOf(key);
        if(index==-1){
            this.con.addFirst(key);
        }
    }
    public void delete(Integer key){
        this.con.remove(key);
    }
    public boolean exist(Integer key){
        int index=this.con.indexOf(key);
        return (index!=-1);
    }
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值