原理
以二进制位来表示数字
例如:第27位为1,第28位为0。表示在map中27存在28不存在
实现
代码
<?php
class bitMap
{
protected $intBitSize = null;
protected $intBitSizeLog2 = null;
protected $map = [];
/**
* bitMap constructor.
* @param $maxArg map最大数
*/
public function __construct($maxArg)
{
$this->intBitSize = PHP_INT_SIZE * 8;
$this->intBitSizeLog2 = log(PHP_INT_SIZE * 8, 2);
$this->map = array_fill(0, (($maxArg>>$this->intBitSizeLog2) + 1), 0);
}
/**
* 添加, 即设置对应位为1
* @param $arg
* @return $this
*/
public function set($arg)
{
if (is_array($arg)) {
foreach ($arg as $v) {
list($index, $position) = $this->getLocation($v);
$this->map[$index] |= 1<<$position;
}
} else {
list($index, $position) = $this->getLocation($arg);
$this->map[$index] |= 1<<$position;
}
return $this;
}
/**
* 判断数字是否存在
* @param $arg
* @return bool
*/
public function get($arg)
{
list($index, $position) = $this->getLocation($arg);
$condition = ($this->map[$index] & 1<<$position) != 0;
return $condition;
}
/**
* 删除, 即设置对应位为0
* @param $arg
* @return $this
*/
public function del($arg)
{
if (is_array($arg)) {
foreach ($arg as $v) {
list($index, $position) = $this->getLocation($v);
$this->map[$index] &= ~(1<<$position);
}
} else {
list($index, $position) = $this->getLocation($arg);
$this->map[$index] &= ~(1<<$position);
}
return $this;
}
/**
* 获取数字对应的位置下标
* @param $arg
* @return array
*/
protected function getLocation($arg)
{
return [
$arg>>$this->intBitSizeLog2,
$arg%$this->intBitSize
];
}
}
测试
<?php
$map = new bitMap(9999);
for ($i=1; $i<10000; $i++) {
$map->set($i);
}
$map->del(123);
$map->del(9998);
var_dump(
[
1 => $map->get(1),
99 => $map->get(99),
123 => $map->get(123),
9998 => $map->get(9998),
9999 => $map->get(9999)
]
);
//array(5) {
// [1]=> bool(true)
// [99]=> bool(true)
// [123]=> bool(false)
// [9998]=> bool(false)
// [9999]=> bool(true)
//}