# 706. Design HashMap
###### tags: `leetcode`,`structure`,`easy`
>ref: https://leetcode.com/problems/design-hashmap/
>
Design a HashMap without using any built-in hash table libraries.
Implement the MyHashMap class:
* MyHashMap() initializes the object with an empty map.
* void put(int key, int value) inserts a (key, value) pair into the HashMap. If the key already exists in the map, update the corresponding value.
* int get(int key) returns the value to which the specified key is mapped, or -1 if this map contains no mapping for the key.
* void remove(key) removes the key and its corresponding value if the map contains the mapping for the key.
>Example 1:
Input
["MyHashMap", "put", "put", "get", "get", "put", "get", "remove", "get"]
[[], [1, 1], [2, 2], [1], [3], [2, 1], [2], [2], [2]]
Output
[null, null, null, 1, -1, null, 1, null, -1]

>1. 越大listnode[] 查找key時間越短 (空間換取時間)
>2. 查找到目標前一個listnode或尾端
```java=
class MyHashMap {
final int size=10000;
ListNode[] list;
public MyHashMap() {
list= new ListNode[size];
}
public void put(int key, int value) {
int bucket= hash(key);
//find key in bucket
ListNode pre=find(bucket,key);
//replace or create
if(pre.next!=null){
//find exist key
pre.next.value=value;
}else{
//no exist key
pre.next=new ListNode(key,value);
}
}
public int get(int key) {
int bucket= hash(key);
//find key in bucket
ListNode pre=find(bucket,key);
if(pre.next!=null){
//find
return pre.next.value;
}else{
//to end no find
return -1;
}
}
public void remove(int key) {
int bucket= hash(key);
//find key in bucket
ListNode pre=find(bucket,key);
//remove
if(pre.next!=null){
pre.next=pre.next.next;
}
}
private int hash(int key){
return key%list.length;
}
private ListNode find(int bucket,int key){
//init bucket
if(list[bucket]==null){
list[bucket]=new ListNode(-1,-1);
}
ListNode cur=list[bucket];
while(cur.next!=null && cur.next.key!=key){
cur=cur.next;
}
return cur;
}
class ListNode{
int key;
int value;
ListNode next;
ListNode(int key,int value){
this.key=key;
this.value=value;
}
}
}
```