哈希表

哈希表的实现

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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
const log = console.log.bind(console)

const ensure = function(condition, message) {
if (!condition) {
log('*** 测试失败', message)
} else {
log('+++ 测试成功')
}
}

class HashTable {
constructor() {
this.data = []
this.size = 101
}

hash(s) {
let r = 0
for (let i = 0; i < s.length; i++) {
let val = s[i]
let v = val.charCodeAt(0)
v = v * 10 ** i
r += v
}
return r
}

index(s) {
let l = this.hash(s)
let i = l % this.size
return i
}

set(key, value) {
let index = this.index(key)
let tag = this.data[index]
let ans = []
if (tag === undefined) {
ans.push([key, value])
this.data[index] = ans
} else {
let i = 0
let status = false
for (i; i < tag.length; i++) {
let k = t[0]
if (k === key) {
t[1] = value
status = true
}
}
if (!status && i === tag.length) {
tag.push([key, value])
}
}
}

get(key, value) {
let result = value
let index = this.index(key)
let tags = this.data[index]
if (tags === undefined) {
return value
}
for (let tag of tags) {
if (tag[0] === key) {
result = tag[1]
}
}
return result
}

has(key) {
let index = this.index(key)
let tags = this.data[index]
if (tags === undefined) {
return false
} else {
for (let tag of tags) {
if (tag[0] === key) {
return true
}
return false
}
}
}
}

刷题

两数之和

三数之和

字符流中第一个不重复的字符

宝石与石头

文章作者: woyao
文章链接: https://chenwoyao.github.io/2021/04/23/数据结构和算法/哈希表/
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 woyao的博客