Golang 資料結構:雜湊表

來源:互聯網
上載者:User
這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。

Golang 中鏈表的實現及常用操作,資料結構系列原文:flaviocopes.com,翻譯已獲作者授權。

概述

雜湊表是和 map 類型的索引值對儲存方式不同(PHP 中的關聯陣列),它的雜湊函數能根據 key 值計算出 key 在數組中的切確位置(索引)。

區別雜湊表與 Golang 的 map、PHP 中的關聯陣列:

實現

常用操作

使用內建的 map 類型來實現雜湊表,並實現以下常用操作:

1
2
3
4
Put()
Remove()
Get()
Size()

類似的,建立通用類型 ValueHashTable 來作為雜湊表的結構類型,其中索引值需實現 Stringer 介面。

代碼實現
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
package hashtable

import (
"github.com/cheekybits/genny/generic"
"sync"
"fmt"
)

type Key generic.Type
type Value generic.Type

type ValueHashTable struct {
items map[int]Value
lock sync.RWMutex
}

// 使用霍納規則在 O(n) 複雜度內產生 key 的雜湊值
func hash(k Key) int {
key := fmt.Sprintf("%s", k)
hash := 0
for i := 0; i < len(key); i++ {
hash = 31*hash + int(key[i])
}
return hash
}

// 新增索引值
func (ht *ValueHashTable) Put(k Key, v Value) {
ht.lock.Lock()
defer ht.lock.Unlock()
h := hash(k)
if ht.items == nil {
ht.items = make(map[int]Value)
}
ht.items[h] = v
}

// 刪除鍵
func (ht *ValueHashTable) Remove(k Key) {
ht.lock.Lock()
defer ht.lock.Unlock()
h := hash(k)
delete(ht.items, h)
}

// 擷取鍵的雜湊值
func (ht *ValueHashTable) Get(k Key) Value {
ht.lock.RLock()
defer ht.lock.RUnlock()
h := hash(k)
return ht.items[h]
}

// 擷取雜湊表的大小
func (ht *ValueHashTable) Size() int {
ht.lock.RLock()
defer ht.lock.RUnlock()
return len(ht.items)
}

測試案例:hashtable_test.go

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.