雜湊表原理及hashmap簡單實現

來源:互聯網
上載者:User

雜湊表也叫做散列表。在各種語言中都有hashmap的實現。其最突出的優點是尋找和插入以及刪除具有常數的時間複雜度

 

我們可以把雜湊表理解為數組+鏈表

數組具有常數複雜度的尋找,為什麼呢,因為數組是在記憶體中連續存放,當我們索引某個位置的元素時候根據索引值自動計算距離數組首元素起始位置的記憶體間隔。然而對於中間插入和中間刪除元素,數組會將待插入位置後面的原素先整體向後移動一個位置再將元素插入到待插入的位置。所以時間複雜度為O(n)對於大規模的數組來說,開銷是很大的。

 

然而鏈表正相反。由於鏈表是儲存在記憶體中不連續的位置,並且鏈表之間是通過鏈表指標連結到一起。前一個元素儲存後一個元素的指標,我們也稱之為前一個元素指向後一個元素。當我們在鏈表中尋找某個元素的時候必須按照鏈表指標遍曆整個鏈表,時間複雜度為O(n)但是針對插入很刪除來說,我們只需要更改待需要操作的鏈表元素的指標即可,時間複雜度為O(1). 

 

那麼我們可以不可以把兩者結合起來組合成一種新的資料結構呢,這種資料結構即能實現常數複雜度的索引也能實現常數複雜度的插入和刪除。當然雜湊表應運而生。

 

雜湊表的原理可以簡述為(簡述插入和索引操作):

插入:當我們插入hashmap['key']=value時,先將key映射為hashcode,然而用hashcode對雜湊表長度模數獲得索引位置。然後將值插入到索引位置。(這裡可能會存在衝突,即相同的Key的hashcode相同)

 

索引:當我們索引某個值的時候,先將key映射為hashcode,然後將key對雜湊表長度模數,然後取出該索引位置上的值。

 

下面我簡單實現了一個雜湊表,這僅僅是為了說明雜湊的原理。

簡單hashmap類定義:

 1 #include<iostream> 2 using namespace std; 3 class MySimpleHashmap 4 { 5 public: 6     int *Array; 7     enum{MaxHashSize=7}; 8  9     int hashcode(int &key);10 11 public:12     MySimpleHashmap();13     ~MySimpleHashmap();14 15     int& operator[](int & key);16 17 };18 19 20 int& MySimpleHashmap::operator [](int& key)21 {22     return Array[hashcode(key)];23 }24 25 26 MySimpleHashmap::MySimpleHashmap()27 {28     Array=new int[MaxHashSize];29     30     for(int i=0;i<MaxHashSize;i++)31     {32         Array[i]=0;33     }34 }35 36 MySimpleHashmap::~MySimpleHashmap()37 {38     delete[] Array;39     Array=NULL;40 }41 42 int MySimpleHashmap::hashcode(int& key)43 {44     while(true)45     {46         if(Array[key%MaxHashSize]==0)47         {48             return key%MaxHashSize;49         }50         else51         {52             key++;53         }54     }55 }

main.c

 1 #include "VpoetHashmap.h" 2 #include <iostream> 3 using namespace std; 4  5 int main() 6 { 7     MySimpleHashmap MyHash; 8      9     int key1=15; //hashkey=110     int key2=16;  //hashkey=211     int key3=9;  //hashkey=2衝突12     int key4=11;   //hashkey=413     int key5=5;    //hashkey=514 15     MyHash[key1]=100;16     MyHash[key2]=200;17     MyHash[key3]=300;18     MyHash[key4]=400;19     MyHash[key5]=500;20 21     cout<<"hash table node1:"<<MyHash.Array[0]<<endl;22     cout<<"hash table node2:"<<MyHash.Array[1]<<endl;23     cout<<"hash table node3:"<<MyHash.Array[2]<<endl;24     cout<<"hash table node4:"<<MyHash.Array[3]<<endl;25     cout<<"

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.