706. diseño de mapas de hash

título Descripción

mapa hash diseño
no utiliza ninguna tabla hash biblioteca incorporada diseñar un mapa hash

En concreto, su diseño debe incluir las siguientes funciones

put (clave, valor): se inserta en el mapa hash (clave, valor) pares de valores. Si existe la clave correspondiente al valor ya, este valor se actualiza.
get (clave): devuelve el valor correspondiente a la clave dada, y si el mapa no contiene esta clave, devuelve -1.
eliminar (tecla): Si hay esta asignación de teclas, eliminar esta pares de valores.

Ejemplo:

HashMap '= new nuevo MyHashMap MyHashMap ();
hashMap.put (1 ,. 1.);
HashMap.put (2, 2);
HashMap.get (1.); // devuelve 1.
HashMap.get (3.); // devuelve -1 ( no encontrado)
hashMap.put (2, 1); // actualizar el valor existente
hashMap.get (2); // devuelve 1
hashMap.remove (2); // datos de la eliminación de clave para el 2
hashMap.get (2 ); // devuelve -1 (no encontrado)

nota:

Todos los valores en el rango [1 1000000] es.
El número total de operaciones en el intervalo [1, 10000].
No utilice la biblioteca de hash incorporado.

código
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;
	}
}
Publicado 75 artículos originales · ganado elogios 0 · Vistas 1487

Supongo que te gusta

Origin blog.csdn.net/qq_34087914/article/details/104809021
Recomendado
Clasificación