-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path2-design-hashset.py
More file actions
58 lines (52 loc) · 1.83 KB
/
Copy path2-design-hashset.py
File metadata and controls
58 lines (52 loc) · 1.83 KB
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
# -------------------------------------------------------
# Design Hashset - https://leetcode.com/explore/challenge/card/august-leetcoding-challenge/549/week-1-august-1st-august-7th/3410/
# -------------------------------------------------------
# Author: Arshad Mehmood
# Github: https://github.com/arshad115
# Blog: https://arshadmehmood.com
# LinkedIn: https://www.linkedin.com/in/arshadmehmood115
# Date : 2020-08-2
# Project: leetcode-august-2020
# -------------------------------------------------------
class MyHashSet:
def __init__(self):
"""
Initialize your data structure here.
"""
self.size = 10000
self.buckets = [[] for _ in range(self.size)]
def add(self, key: int) -> None:
bucket, i = self.index(key)
if i == -1:
bucket.append(key)
def remove(self, key: int) -> None:
bucket, i = self.index(key)
if i != -1:
bucket.remove(key)
else:
return
def contains(self, key: int) -> bool:
"""
Returns true if this set contains the specified element
"""
bucket, i = self.index(key)
return i!= -1
def hash(self, key: int) -> bool:
return key % self.size
def index(self, key: int) -> bool:
hash = self.hash(key)
bucket = self.buckets[hash] # Got the bucket, now go to the key
for i, b in enumerate(bucket):
if b == key:
return bucket,i
return bucket,-1
# Your MyHashSet object will be instantiated and called as such:
hashSet = MyHashSet()
hashSet.add(1)
hashSet.add(2)
print(hashSet.contains(1)) # returns true
print(hashSet.contains(3)) # returns false (not found)
hashSet.add(2)
print(hashSet.contains(2)) # returns true
hashSet.remove(2)
print(hashSet.contains(2)) # returns false (already removed)