Skip to content

705. Design HashSet 👍

  • Time: $O(1)$
  • Space: $O(n)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
class MyHashSet {
 public:
  /** Initialize your data structure here. */
  MyHashSet() : set(1000001) {}

  void add(int key) {
    set[key] = true;
  }

  void remove(int key) {
    set[key] = false;
  }

  /** Returns true if this set contains the specified element */
  bool contains(int key) {
    return set[key];
  }

 private:
  vector<bool> set;
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
class MyHashSet {
  /** Initialize your data structure here. */
  public MyHashSet() {
    set = new boolean[1000001];
  }

  public void add(int key) {
    set[key] = true;
  }

  public void remove(int key) {
    set[key] = false;
  }

  /** Returns true if this set contains the specified element */
  public boolean contains(int key) {
    return set[key];
  }

  private boolean[] set = new boolean[1000001];
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
class MyHashSet:
  def __init__(self):
    self.set = [False] * 1000001

  def add(self, key: int) -> None:
    self.set[key] = True

  def remove(self, key: int) -> None:
    self.set[key] = False

  def contains(self, key: int) -> bool:
    return self.set[key]
Back to top