Leetcode 705. Design HashSet

文章作者:Tyan
博客:noahsnail.com  |  CSDN  |  简书

1. Description

Design HashSet

2. Solution

  • Version 1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class MyHashSet:

def __init__(self):
self.hashset = []


def add(self, key: int) -> None:
if key not in self.hashset:
self.hashset.append(key)


def remove(self, key: int) -> None:
if key in self.hashset:
self.hashset.remove(key)


def contains(self, key: int) -> bool:
if key in self.hashset:
return True
return False
  • Version 2
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class MyHashSet:
def __init__(self):
self.hashset = [False] * 1000001


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


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


def contains(self, key: int) -> bool:
return self.hashset[key]
  • Version 3
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class MyHashSet:

def __init__(self):
self.hashset = [[] for _ in range(1000)]


def add(self, key: int) -> None:
index = self.hash(key)
if key not in self.hashset[index]:
self.hashset[index].append(key)


def remove(self, key: int) -> None:
index = self.hash(key)
if key in self.hashset[index]:
self.hashset[index].remove(key)


def contains(self, key: int) -> bool:
index = self.hash(key)
return key in self.hashset[index]


def hash(self, key):
return key % 1000

Reference

  1. https://leetcode.com/problems/design-hashset/
如果有收获,可以请我喝杯咖啡!