#705 设计哈希集合

206 阅读1分钟

题目描述

leetcode-cn.com/problems/de…

分析

实现 HashMap 的几个方法

算法

哈希

过程

实现所有要求的方法

instance properties

base

为保证尽可能减小哈希冲突,应选取一个质数,这里我和官方题解一样选取的是 769

data

存放所有的数据,为长度为 base 的数组,因为我采用的是拉链法解决哈希冲突,因此每个位置是一个空数组

this.data = new Array(this.base).fill(0).map(() => new Array())

自定义方法 MyHashSet.prototype.hash

通过取余将传过来的 key map 到数组下标

MyHashSet.prototype.add

作用:增加一个哈希 key

已存在:如果已经存在 key 对应下标元素,则不进行操作 其他:通过 this.hash 方法找到对应数组,放进去这个 key

MyHashSet.prototype.remove

作用:移除一个元素

通过 this.hash 找到对应数组

查找 key,找到则删除

MyHashSet.prototype.contains

作用:查看哈希中是否存在 key

this.hash 找数组 -> 查数组中有无对应 key

代码

var MyHashSet = function() {
    this.base = 769
    this.data = new Array(this.base).fill(0).map(() => new Array())
};

/** 
 * @param {number} key
 * @return {void}
 */
MyHashSet.prototype.add = function(key) {
    if (this.contains(key)) return
    const ind = this.hash(key)
    this.data[ind].push(key)
};

/** 
 * @param {number} key
 * @return {void}
 */
MyHashSet.prototype.remove = function (key) {
        const h = this.hash(key)
        const it = this.data[h]
        for (let i = 0; i < it.length; ++i) {
          if (it[i] === key) {
            it.splice(i, 1)
            return
          }
        }
      }

/** 
 * @param {number} key
 * @return {boolean}
 */
MyHashSet.prototype.contains = function(key) {
    const ind = this.hash(key)
    for (const x of this.data[ind]) {
        if (x === key) return true
    }
    
    return false
};

/** 
 * @param {number} key
 * @return {number}
 */
MyHashSet.prototype.hash = function(key) {
    return key % this.base
};

/**
 * Your MyHashSet object will be instantiated and called as such:
 * var obj = new MyHashSet()
 * obj.add(key)
 * obj.remove(key)
 * var param_3 = obj.contains(key)
 */