在PHP中,哈希表是通过关联数组实现的。当两个或多个键产生相同的哈希值时,就会发生冲突。处理哈希冲突的方法有以下几种:
class HashTable {
private $size;
private $table;
public function __construct($size) {
$this->size = $size;
$this->table = array_fill(0, $size, []);
}
private function hash($key) {
return abs(crc32($key)) % $this->size;
}
public function set($key, $value) {
$index = $this->hash($key);
foreach ($this->table[$index] as $entry) {
if ($entry[0] === $key) {
$entry[1] = $value;
return;
}
}
$this->table[$index][] = [$key, $value];
}
public function get($key) {
$index = $this->hash($key);
foreach ($this->table[$index] as $entry) {
if ($entry[0] === $key) {
return $entry[1];
}
}
return null;
}
}
class HashTable {
private $size;
private $table;
public function __construct($size) {
$this->size = $size;
$this->table = array_fill(0, $size, null);
}
private function hash($key) {
return abs(crc32($key)) % $this->size;
}
public function set($key, $value) {
$index = $this->hash($key);
while ($this->table[$index] !== null) {
if ($this->table[$index][0] === $key) {
$this->table[$index] = [$key, $value];
return;
}
$index = ($index + 1) % $this->size;
}
$this->table[$index] = [$key, $value];
}
public function get($key) {
$index = $this->hash($key);
while ($this->table[$index] !== null) {
if ($this->table[$index][0] === $key) {
return $this->table[$index][1];
}
$index = ($index + 1) % $this->size;
}
return null;
}
}
这些方法可以根据具体应用场景和需求选择。链地址法在大多数情况下性能较好,但可能导致内存占用较高;开放寻址法在内存利用方面更优,但在最坏情况下性能较差。