diff --git a/Design HashSet.py b/Design HashSet.py new file mode 100644 index 00000000..858464fa --- /dev/null +++ b/Design HashSet.py @@ -0,0 +1,63 @@ +# Time Complexity: O(1) for add, remove, and contains +# Space Complexity: O(1), because the maximum key range is fixed +# Did this code successfully run on LeetCode: Yes + +class MyHashSet(object): + + def __init__(self): + self.primaryBuckets = 1000 + self.secondaryBuckets = 1000 + self.storage = [None] * self.primaryBuckets + + def getPrimaryHash(self, key): + return key % self.primaryBuckets + + def getSecondaryHash(self, key): + return key // self.secondaryBuckets + + + def add(self, key): + """ + :type key: int + :rtype: None + """ + primaryHash = self.getPrimaryHash(key) + if self.storage[primaryHash] == None: + if primaryHash == 0: + self.storage[primaryHash] = [False] * (self.secondaryBuckets + 1) + else: + self.storage[primaryHash] = [False] * self.secondaryBuckets + secondaryHash = self.getSecondaryHash(key) + self.storage[primaryHash][secondaryHash] = True + + + def remove(self, key): + """ + :type key: int + :rtype: None + """ + primaryHash = self.getPrimaryHash(key) + if self.storage[primaryHash] is None: + return + secondaryHash = self.getSecondaryHash(key) + self.storage[primaryHash][secondaryHash] = False + + + def contains(self, key): + """ + :type key: int + :rtype: bool + """ + primaryHash = self.getPrimaryHash(key) + if self.storage[primaryHash] is None: + return False + secondaryHash = self.getSecondaryHash(key) + return self.storage[primaryHash][secondaryHash] + + +# Your MyHashSet object will be instantiated and called as such: +obj = MyHashSet() +obj.add(1) +obj.add(2) +obj.remove(1) +print(obj.contains(1)) \ No newline at end of file diff --git a/MinStack.py b/MinStack.py new file mode 100644 index 00000000..92a5634f --- /dev/null +++ b/MinStack.py @@ -0,0 +1,55 @@ +# Time Complexity: O(1) for push, pop, top, and getMin +# Space Complexity: O(n) + +# Did this code successfully run on LeetCode: Yes + +class MinStack(object): + + def __init__(self): + self.st, self.minSt = [], [] + self.min = float("inf") + + + def push(self, value): + """ + :type value: int + :rtype: None + """ + if value <= self.min: + self.minSt.append(self.min) + self.min = value + self.st.append(value) + + + + def pop(self): + """ + :rtype: None + """ + if self.min == self.st.pop(): + self.min = self.minSt.pop() + + + def top(self): + """ + :rtype: int + """ + return self.st[-1] + + + def getMin(self): + """ + :rtype: int + """ + return self.min + + + +# Your MinStack object will be instantiated and called as such: +obj = MinStack() +obj.push(2) +obj.push(1) +obj.push(4) +obj.pop() +print(obj.top()) +print(obj.getMin()) \ No newline at end of file