diff --git a/MinStack.java b/MinStack.java new file mode 100644 index 00000000..b999746f --- /dev/null +++ b/MinStack.java @@ -0,0 +1,36 @@ +class MinStack { + + private int[] stack; + private int[] minStack; + private int top; + + public MinStack() { + stack = new int[30000]; + minStack = new int[30000]; + top = -1; + } + + public void push(int val) { + stack[++top] = val; + + if (top == 0) { + minStack[top] = val; + } else { + minStack[top] = Math.min(val, minStack[top - 1]); + } + } + + public void pop() { + minStack[top] = Integer.MAX_VALUE; + stack[top] = Integer.MAX_VALUE; + top--; + } + + public int top() { + return stack[top]; + } + + public int getMin() { + return minStack[top]; + } +} diff --git a/MyHashSet.java b/MyHashSet.java new file mode 100644 index 00000000..2c70ed9e --- /dev/null +++ b/MyHashSet.java @@ -0,0 +1,53 @@ +class MyHashSet { + + private static final int HASH_SIZE = 78727; // Chose a very large prime number + private static final int BUCKET_SIZE = 70; // Each bucket size + + private int[][] buckets; + private int[] bucketCount; + + public MyHashSet() { + buckets = new int[HASH_SIZE][BUCKET_SIZE]; + bucketCount = new int[HASH_SIZE]; + } + + private int hash(int key) { + return key % HASH_SIZE; + } + + public void add(int key) { + int h = hash(key); + + // check if exists + for (int i = 0; i < bucketCount[h]; i++) { + if (buckets[h][i] == key) return; + } + + // insert if space available + if (bucketCount[h] < BUCKET_SIZE) { + buckets[h][bucketCount[h]] = key; + bucketCount[h]++; + } + // if no space space available not inserted but we know 0 <= key <= 10^6 + } + + public void remove(int key) { + int h = hash(key); + + for (int i = 0; i < bucketCount[h]; i++) { + if (buckets[h][i] == key) { + buckets[h][i] = -1; + bucketCount[h]--; + return; + } + } + } + + public boolean contains(int key) { + int h = hash(key); + for (int i = 0; i < bucketCount[h]; i++) { + if (buckets[h][i] == key) return true; + } + return false; + } +}