diff --git a/MyHashMap.java b/MyHashMap.java new file mode 100644 index 00000000..50d8b780 --- /dev/null +++ b/MyHashMap.java @@ -0,0 +1,79 @@ +// Time Complexity : O(1) average +// Space Complexity :O(n + 10000) +// Did this code successfully run on Leetcode : yes +// Any problem you faced while coding this : No + + +// Your code here along with comments explaining your approach +class MyHashMap { + + class Node{ + int key, val; + Node next; + + public Node(int key, int val){ + this.key = key; + this.val = val; + } + } + + private Node[] storage; + + public MyHashMap() { + this.storage = new Node[10000]; + } + + public int hash(int key){ + return key%10000; + } + + public Node find(Node head, int key){ + Node prev = null; + Node curr = head; + while(curr != null && curr.key != key){ + prev = curr; + curr = curr.next; + } + + return prev; + } + + public void put(int key, int value) { + int idx = hash(key); + if(storage [idx] == null){ + storage[idx] = new Node(-1,-1); + } + + Node prev = find(storage[idx], key); + if(prev.next !=null){ + prev.next.val = value; + }else{ + prev.next = new Node(key,value); + } + } + + public int get(int key) { + int idx = hash(key); + if(storage[idx] == null) return -1; + Node prev = find(storage[idx], key); + + if(prev.next !=null){ + return prev.next.val; + } + + return -1; + } + + public void remove(int key) { + int idx = hash(key); + if(storage[idx] == null){ + return; + } + Node prev = find(storage[idx], key); + if(prev.next == null){ + return; + } + prev.next = prev.next.next; + } +} + diff --git a/MyQueue.java b/MyQueue.java new file mode 100644 index 00000000..9e8aedf5 --- /dev/null +++ b/MyQueue.java @@ -0,0 +1,55 @@ +// Time Complexity : O(1) average +// Space Complexity :O(n) +// Did this code successfully run on Leetcode : yes +// Any problem you faced while coding this : No + +class MyQueue { + + Stack in; + Stack out; + public MyQueue() { + in = new Stack<>(); + out = new Stack<>(); + } + + public void push(int x) { + in.push(x); + } + + public int pop() { + if(out.isEmpty()){ + while(!in.isEmpty()){ + out.push(in.pop()); + } + } + return out.pop(); + } + + public int peek() { + if(out.isEmpty()){ + while(!in.isEmpty()){ + out.push(in.pop()); + } + } + + return out.peek(); + } + + public boolean empty() { + + if(in.isEmpty() && out.isEmpty()){ + return true; + } + + return false; + } +} + +/** + * Your MyQueue object will be instantiated and called as such: + * MyQueue obj = new MyQueue(); + * obj.push(x); + * int param_2 = obj.pop(); + * int param_3 = obj.peek(); + * boolean param_4 = obj.empty(); + */ \ No newline at end of file diff --git a/Sample.java b/Sample.java deleted file mode 100644 index 1739a9cb..00000000 --- a/Sample.java +++ /dev/null @@ -1,7 +0,0 @@ -// Time Complexity : -// Space Complexity : -// Did this code successfully run on Leetcode : -// Any problem you faced while coding this : - - -// Your code here along with comments explaining your approach