Leetcode in Java && Oracle
421 subscribers
8 photos
397 files
400 links
Second channel: @codeforces_java

Let's Develop Together!
Download Telegram
runtime.png
12.4 KB
#N706. Design HashMap
problem link

#solution
class MyHashMap {
public ListNode[] nodes = new ListNode[10000];
public MyHashMap() {

}

public void put(int key, int value) {
int index = key%nodes.length;
if(nodes[index]==null){
nodes[index] = new ListNode(-1, -1);
}
ListNode prev=find(nodes[index], key);
if(prev.next==null)
prev.next=new ListNode(key, value);
else
prev.next.val = value;
}

public int get(int key) {
int index = key%nodes.length;
if(nodes[index] == null) return -1;
ListNode prev = find(nodes[index], key);

if(prev.next == null) return -1;
return prev.next.val;
}

public void remove(int key) {
int index = key%nodes.length;
if(nodes[index] == null) return;
ListNode prev = find(nodes[index], key);
if(prev.next == null) return;
prev.next=prev.next.next;
}
CarbonNowShBot.png
327.8 KB
    ListNode find(ListNode node, int key){
ListNode head = node, prev=null;
while(head!=null && head.key !=key){
prev=head;
head=head.next;
}
return prev;
}

class ListNode{
int key, val;
ListNode next;
public ListNode(int key, int val){
this.key = key;
this.val = val;
}
}
}