Title Description
Hash map design
does not use any hash table built-in library design a hash map
Specifically, your design should include the following functions
put (key, value): inserted into the hash map (key, value) value pairs. If the key corresponding to the value already exists, this value is updated.
get (key): returns the value corresponding to the given key, and if the map does not contain this key, returns -1.
remove (key): If there is this key mapping, delete this value pairs.
Example:
HashMap '= new new MyHashMap MyHashMap ();
hashMap.put (. 1,. 1);
hashMap.put (2, 2);
HashMap.get (. 1); // returns. 1
HashMap.get (. 3); // returns -1 ( not found)
hashMap.put (2, 1); // update the existing value
hashMap.get (2); // returns 1
hashMap.remove (2); // delete key data for the 2
hashMap.get (2 ); // returns -1 (not found)
note:
All values in the range [1 1000000] is.
The total number of operations in the range [1, 10000].
Do not use the built-in hash library.
Code
package pid706;
import java.util.List;
import java.util.ArrayList;
import java.util.LinkedList;
class MyHashMap {
private int key_space;
private List<Bucket> hash_table;
public MyHashMap(){
this.key_space = 2069;
this.hash_table = new ArrayList<Bucket>();
for(int i=0;i<this.key_space;i++){
this.hash_table.add(new Bucket());
}
}
public void put(int key,int value){
int hash_key = key % this.key_space;
this.hash_table.get(hash_key).update(key,value);
// update是Bucket类中的方法
}
public int get(int key){
int hash_key = key % this.key_space;
return this.hash_table.get(hash_key).get(key);
// get是Bucket类中的方法
}
public void remove(int key){
int hash_key = key % this.key_space;
this.hash_table.get(hash_key).remove(key);
// remove是Bucket类中的方法
}
}
class Bucket{
// 一个桶对象中存放多个映射对
private List<Pair<Integer,Integer>> bucket;
public Bucket(){
this.bucket = new LinkedList<Pair<Integer,Integer>>();
}
public Integer get(Integer key){
for(Pair<Integer,Integer> pair : this.bucket){
if(pair.first.equals(key)){
return pair.second;
}
}
return -1;
}
public void update(Integer key,Integer value){
for(Pair<Integer,Integer> pair : this.bucket){
if(pair.first.equals(key)){
// key存在:更新
pair.second = value;
return;
}
}
// key不存在:创建
this.bucket.add(new Pair<Integer,Integer>(key,value));
}
public void remove(Integer key){
for(Pair<Integer,Integer> pair : this.bucket){
if(pair.first.equals(key)){
this.bucket.remove(pair);// remove(Object o)方法
break;
}
}
}
}
class Pair<U,V>{
public U first;
public V second;
public Pair(U first,V second){
this.first = first;
this.second = second;
}
}