【Leetcode 705 】设计哈希集合——数组嵌套链表(限制哈希Key)

55 阅读2分钟

 题目

不使用任何内建的哈希表库设计一个哈希集合(HashSet)。

实现 MyHashSet 类:

  • void add(key) 向哈希集合中插入值 key 。
  • bool contains(key) 返回哈希集合中是否存在这个值 key 。
  • void remove(key) 将给定值 key 从哈希集合中删除。如果哈希集合中没有这个值,什么也不做。

示例:

输入:
["MyHashSet", "add", "add", "contains", "contains", "add", "contains", "remove", "contains"]
[[], [1], [2], [1], [3], [2], [2], [2], [2]]
输出:
[null, null, null, true, false, null, true, null, false]

解释:
MyHashSet myHashSet = new MyHashSet();
myHashSet.add(1);      // set = [1]
myHashSet.add(2);      // set = [1, 2]
myHashSet.contains(1); // 返回 True
myHashSet.contains(3); // 返回 False ,(未找到)
myHashSet.add(2);      // set = [1, 2]
myHashSet.contains(2); // 返回 True
myHashSet.remove(2);   // set = [1]
myHashSet.contains(2); // 返回 False ,(已移除)

提示:

  • 0 <= key <= 106
  • 最多调用 104 次 addremove 和 contains

时间复杂度:O()

空间复杂度:O(n+b)

题解 

class MyHashSet {
  //创建哈希集合大小,其表现方式为数组
  BASE: number;

  //二维数组,其第二维表现方式为链表
  data: number[][];
  constructor() {
    //初始化集合大小为 1111,注意:该值最好是质数
    this.BASE = 1111;
    // 初始化集合,长度为 BASE,其中每一个值都是一个链表,存储着值
    this.data = Array(this.BASE)
      .fill(0)
      .map(() => new Array());
  }

  //   哈希函数,将哈希的key控制在一定范围,如add一万个数据,则可能要有一万个key
  //   哈希函数通过 取模,将key控制在固定范围,相同key的,但不同值,则用链表的方式存储
  //   如 key = 1 , BASE = 1111   则hashKey = 1
  //      key = 1112 , BASE = 1111  则hashKey = 1
  hash(key: number) {
    return key % this.BASE;
  }

  // 新增
  add(key: number): void {
    // 获取该值的 hashKey
    const hashKey = this.hash(key);

    // 循环该 hashKey 的 hash值
    for (const ele of this.data[hashKey]) {
      // 有此数据,则不新增,直接返回
      if (ele === key) return;
    }
    // 新增数据
    this.data[hashKey].push(key);
  }

  remove(key: number): void {
    // 获取该值的 hashKey
    const hashKey = this.hash(key);

    // 循环该 hashKey 的 hash值
    let d = this.data[hashKey];
    for (let i = 0; i < d.length; i++) {
      // 找到则删除
      if (key === d[i]) {
        d.splice(i, 1);
        return;
      }
    }
  }

  contains(key: number): boolean {
    // 获取该值的 hashKey
    const hashKey = this.hash(key);

    // 循环该 hashKey 的 hash值
    for (const ele of this.data[hashKey]) {
      // 包含此值,则返回true
      if (ele === key) return true;
    }
    return false;
  }
}