1. 程式人生 > 其它 >雜湊函式自我實現(設計雜湊對映)

雜湊函式自我實現(設計雜湊對映)

技術標籤:雜湊資料結構雜湊表

不使用任何內建的雜湊表庫設計一個雜湊對映

設計包含以下內容:

put(key, value):向雜湊對映中插入(鍵,值)的數值對。如果鍵對應的值已經存在,更新這個值。
get(key):返回給定的鍵所對應的值,如果對映中不包含這個鍵,返回-1。
remove(key):如果對映中存在這個鍵,刪除這個數值對。
力扣原題傳送

本題我使用的是鏈地址法解決雜湊衝突,vector容器存放雜湊節點的地址;

結構體定義:

Node:
在這裡插入圖片描述

struct Node
{
	int key;//存放key值
	int val;//存放對應的value
	Node* next;//指向結點的指標
//自定義引數列表初始化節點 Node(int key, int val) :key(key), val(val), next(nullptr) {} };

類定義:

class MyHashMap {
public:
	vector<Node*> vec;//用一個存放節點地址的容器充當頭結點
	int length = 1000;
	/** Initialize your data structure here. */
	MyHashMap() {
		//vec = vector<Node*>(length, new Node(-1, -1));//初始化vec容器
		//生成length長度的節點,並初始化key、val域為-1、-1,將其地址依次放入vec中
vec.resize(length);//給vec分配空間 vec.assign(length, new Node(-1, -1)); } /** value will always be non-negative. */ void put(int key, int value) { Node* head = vec[key % length];//雜湊函式尋找插入位置 Node* prevNode = head;//設定前節點 head = head->next;//head先走一步 while (head) { if (head->key == key)//說明雜湊中存在該節點
{ head->val = value;//更新val值 return; } head = head->next; prevNode = prevNode->next; } //出迴圈,說明沒找到這個節點,直接插入 Node* newNode = new Node(key, value);//初始化該節點key值val值 prevNode->next = newNode;//將新節點連結到雜湊表 } /** Returns the value to which the specified key is mapped, or -1 if this map contains no mapping for the key */ int get(int key) { Node* head = vec[key % length];//雜湊函式尋找位置 head = head->next; while (head) { if (head->key == key) { //找到節點,直接返回 return head->val; } else if (head->key == -1) return -1;//未找到 head = head->next; } return -1; } /** Removes the mapping of the specified value key if this map contains a mapping for the key */ void remove(int key) { Node* head = vec[key % length];//雜湊函式尋找位置 Node* prevNode = head; head = head->next;//head:先走一步了兄弟! while (head) { if (head->key == key) { prevNode->next = head->next; return; } else if (head->key == -1) return; head = head->next; prevNode = prevNode->next; } } };