Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 41 additions & 0 deletions hashMap.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
# Use a 2D list to simulate a hash map with double hashing for collision resolution
# The outer list (store) has a fixed size, and each element is either None or an inner list (bucket). The inner list (bucket) is initialized when needed and has a fixed size
# The key is mapped to an index in the outer list using modulo operation. The key is mapped to an index in the inner list using integer division
class MyHashMap:
def __init__(self):
self.storeSize = 1000
self.bucketSize = 1000
self.store = [None] * self.storeSize

def getStoreIndex(self, key: int) -> int:
return key % self.storeSize

def getBucketIndex(self, key: int) -> int:
return key // self.storeSize

def put(self, key: int, value: int) -> None:
storeIndex = self.getStoreIndex(key)
if self.store[storeIndex]:
bucketIndex = self.getBucketIndex(key)
self.store[storeIndex][bucketIndex] = value
return
if storeIndex == 0:
self.store[storeIndex] = [-1] * (self.bucketSize + 1)
else:
self.store[storeIndex] = [-1] * self.bucketSize
bucketIndex = self.getBucketIndex(key)
self.store[storeIndex][bucketIndex] = value

def get(self, key: int) -> int:
storeIndex = self.getStoreIndex(key)
if not self.store[storeIndex]:
return -1
bucketIndex = self.getBucketIndex(key)
return self.store[storeIndex][bucketIndex]

def remove(self, key: int) -> None:
storeIndex = self.getStoreIndex(key)
if not self.store[storeIndex]:
return
bucketIndex = self.getBucketIndex(key)
self.store[storeIndex][bucketIndex] = -1
23 changes: 23 additions & 0 deletions queueUsingStack.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
# Use 2 lists to simulate 2 stacks. inStack is used to push elements. outStack is used to pop elements
# When outStack is empty, we pop all elements from inStack and push them to outStack
# This way, the order of elements is reversed and we can get the front element of the queue from the top of outStack
class MyQueue:
def __init__(self):
self.inStack = []
self.outStack = []

def push(self, x: int) -> None:
self.inStack.append(x)

def pop(self) -> int:
self.peek()
return self.outStack.pop()

def peek(self) -> int:
if len(self.outStack) == 0:
while len(self.inStack) != 0:
self.outStack.append(self.inStack.pop())
return self.outStack[-1]

def empty(self) -> bool:
return len(self.inStack) == 0 and len(self.outStack) == 0