diff --git a/MinStack.java b/MinStack.java new file mode 100644 index 00000000..247afc4f --- /dev/null +++ b/MinStack.java @@ -0,0 +1,71 @@ +import java.util.Stack; + +/* +Problem 2: +Design MinStack (https://leetcode.com/problems/min-stack/) + */ +public class MinStack { + Stack st; + Stack minSt; + int min; + public MinStack() { + this.st = new Stack<>(); + this.minSt = new Stack<>(); + this.min = Integer.MAX_VALUE; + minSt.push(min); + } + + public void push(int val) { + min = Math.min(val,min); + st.push(val); + minSt.push(min); + } + + public void pop() { + st.pop(); + minSt.pop(); + min = minSt.peek(); + } + + public int top() { + return st.peek(); + } + + public int getMin() { + return minSt.peek(); + } +} + + class MinStack2 { + Stack st; + int min; + public MinStack2() { + this.st = new Stack<>(); + + this.min = Integer.MAX_VALUE; + + } + + public void push(int val) { + if(min>=val){ + st.push(min); + } + min = Math.min(val,min); + st.push(val); + } + + public void pop() { + if(st.pop() == min ){ + min = st.pop(); + } + + } + + public int top() { + return st.peek(); + } + + public int getMin() { + return min; + } +} diff --git a/MyHashSet.java b/MyHashSet.java new file mode 100644 index 00000000..78d636aa --- /dev/null +++ b/MyHashSet.java @@ -0,0 +1,55 @@ +//https://leetcode.com/problems/design-hashset/ +public class MyHashSet { + int primarySize ; + int secondarySize; + boolean[][] data; + + public MyHashSet() { + this.primarySize = 1001; + this.secondarySize = 1000; + this.data = new boolean[primarySize][]; + } + + public void add(int key) { + int primaryHash = getPrimaryHash(key); + if(this.data[primaryHash]==null){ + this.data[primaryHash] = new boolean [secondarySize]; + } + int secondaryHash = getSecondaryHash(key); + this.data[primaryHash][secondaryHash] = true; + } + + public void remove(int key) { + int primaryHash = getPrimaryHash(key); + if(this.data[primaryHash]==null){ + return ; + } + int secondaryHash = getSecondaryHash(key); + this.data[primaryHash][secondaryHash] = false; + } + + public boolean contains(int key) { + int primaryHash = getPrimaryHash(key); + if(this.data[primaryHash]==null){ + return false; + } + int secondaryHash = getSecondaryHash(key); + return this.data[primaryHash][secondaryHash]; + + } + + public int getPrimaryHash(int key){ + return key/this.primarySize; + } + public int getSecondaryHash(int key){ + return key%this.secondarySize; + } +} + +/** + * Your MyHashSet object will be instantiated and called as such: + * MyHashSet obj = new MyHashSet(); + * obj.add(key); + * obj.remove(key); + * boolean param_3 = obj.contains(key); + */ \ No newline at end of file