-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLeetcode May Daily Challenge 30.py
74 lines (63 loc) · 1.88 KB
/
Leetcode May Daily Challenge 30.py
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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
class MyHashSet(object):
def __init__(self):
"""
Initialize your data structure here.
"""
self.keyRange = 769
self.bucketArray = [Bucket() for i in range(self.keyRange)]
def _hash(self, key):
return key % self.keyRange
def add(self, key):
"""
:type key: int
:rtype: None
"""
bucketIndex = self._hash(key)
self.bucketArray[bucketIndex].insert(key)
def remove(self, key):
"""
:type key: int
:rtype: None
"""
bucketIndex = self._hash(key)
self.bucketArray[bucketIndex].delete(key)
def contains(self, key):
"""
Returns true if this set contains the specified element
:type key: int
:rtype: bool
"""
bucketIndex = self._hash(key)
return self.bucketArray[bucketIndex].exists(key)
class Node:
def __init__(self, value, nextNode=None):
self.value = value
self.next = nextNode
class Bucket:
def __init__(self):
# a pseudo head
self.head = Node(0)
def insert(self, newValue):
# if not existed, add the new element to the head.
if not self.exists(newValue):
newNode = Node(newValue, self.head.next)
# set the new head.
self.head.next = newNode
def delete(self, value):
prev = self.head
curr = self.head.next
while curr is not None:
if curr.value == value:
# remove the current node
prev.next = curr.next
return
prev = curr
curr = curr.next
def exists(self, value):
curr = self.head.next
while curr is not None:
if curr.value == value:
# value existed already, do nothing
return True
curr = curr.next
return False