-
Notifications
You must be signed in to change notification settings - Fork 0
/
DesignHashMap.php
126 lines (94 loc) · 2.69 KB
/
DesignHashMap.php
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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
<?php
namespace QueueAndStack\QueueFirstInFirstOut\DesignHashSet;
// 不使用任何内建的哈希表库设计一个哈希映射
//
// 具体地说,你的设计应该包含以下的功能
//
// put(key, value):向哈希映射中插入(键,值)的数值对。如果键对应的值已经存在,更新这个值。
// get(key):返回给定的键所对应的值,如果映射中不包含这个键,返回-1。
// remove(key):如果映射中存在这个键,删除这个数值对。
class Node
{
public $key;
public $val;
public $next;
/**
* Node constructor.
*
* @param $key
* @param $val
* @param $next
*/
public function __construct($key, $val, $next = null)
{
$this->key = $key;
$this->val = $val;
$this->next = $next;
}
}
class MyHashMap
{
protected $size = 9;
protected $data;
public function __construct()
{
$this->data = array_fill(0, $this->size-1, null);
}
public function put($key, $value)
{
$hashKey = $this->hashKey($key);
$head = $this->data[$hashKey];
if (is_null($head)) {
$this->data[$hashKey] = new Node($key, $value);
return;
}
$end = $head;
while (! is_null($head)) {
if ($head->key === $key) {
$head->val = $value;
return;
}
$end = $head;
$head = $head->next;
}
$end->next = new Node($key, $value);
}
public function get($key)
{
$hashKey = $this->hashKey($key);
$head = $this->data[$hashKey];
if (is_null($head)) {
return -1;
}
while (! is_null($head)) {
if ($head->key === $key) {
return $head->val;
}
$head = $head->next;
}
return -1;
}
public function remove($key)
{
$hashKey = $this->hashKey($key);
$head = $this->data[$hashKey];
if (is_null($head)) {
return;
}
if ($head->key === $key) {
$this->data[$hashKey] = $head->next;
return;
}
while (! is_null($head->next)) {
if ($head->next->key === $key) {
$head->next = $head->next->next;
return;
}
$head = $head->next;
}
}
protected function hashKey($key)
{
return $key%$this->size;
}
}