-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhash_table.go
More file actions
64 lines (51 loc) · 1.19 KB
/
Copy pathhash_table.go
File metadata and controls
64 lines (51 loc) · 1.19 KB
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
60
61
62
63
64
package main
type CustomHashTable struct {
size int
data []*CustomHashTableItem
}
type CustomHashTableItem struct {
key int
value int
next *CustomHashTableItem
}
// on veut en espace O(K), avec K le nombre de clés utilisées
// et pas O(|U|) avec U l'univers de clés
// on veut implémenter la recherche, l'insertion et la suppression en O(1) en termes de temps, en moyenne
func NewCustomHashTable(size int) *CustomHashTable {
return &CustomHashTable{
size: size,
data: make([]*CustomHashTableItem, size),
}
}
func (h *CustomHashTable) Hash(key int) int {
return key % h.size
}
func (h *CustomHashTable) HashSearch(key int) int {
index := h.Hash(key)
row := h.data[index]
if row == nil {
panic("hash table is empty or key not found")
}
for item := row; item != nil; item = item.next {
if item.key == key {
return item.value
}
}
panic("key not found in hash table")
}
func (h *CustomHashTable) HashInsert(key, value int) {
index := h.Hash(key)
row := h.data[index]
item := &CustomHashTableItem{
key: key,
value: value,
next: nil,
}
if row != nil {
h.data[index] = item
} else {
// on insère en tête de liste
item.next = row
h.data[index] = item
}
}