-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDesignHashSet.php
93 lines (70 loc) · 1.91 KB
/
DesignHashSet.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
<?php
namespace QueueAndStack\QueueFirstInFirstOut\DesignHashSet;
// 不使用任何内建的哈希表库设计一个哈希集合
//
// 具体地说,你的设计应该包含以下的功能
//
// add(value):向哈希集合中插入一个值。
// contains(value) :返回哈希集合中是否存在这个值。
// remove(value):将给定值从哈希集合中删除。如果哈希集合中没有这个值,什么也不做。
class MyHashSet
{
protected $size = 9;
protected $data;
public function __construct()
{
$this->data = array_fill(0, $this->size - 1, []);
}
/**
* @param Integer $key
* @return NULL
*/
public function add($key)
{
if ($this->contains($key)) {
return;
}
$hashKey = $this->hashKey($key);
$collection = &$this->data[$hashKey];
$collection[] = $key;
}
/**
* @param Integer $key
* @return NULL
*/
public function remove($key)
{
if (! $this->contains($key)) {
return;
}
$hashKey = $this->hashKey($key);
$collection = &$this->data[$hashKey];
for ($i = 0, $l = count($collection); $i < $l; ++ $i) {
if ($collection[$i] === $key) {
unset($collection[$i]);
$collection = array_values($collection);
return;
}
}
}
/**
* Returns true if this set contains the specified element
*
* @param Integer $key
* @return Boolean
*/
public function contains($key)
{
$collection = $this->data[$this->hashKey($key)];
for ($i = 0, $l = count($collection); $i < $l; ++ $i) {
if ($collection[$i] === $key) {
return true;
}
}
return false;
}
protected function hashKey($key)
{
return $key % $this->size;
}
}