class TitleOne
{
private $nums;
private $target;
public function __construct($nums, $target)
{
if (!is_array($nums)) {
throw new InvalidArgumentException('第一个参数必须是数组');
}
if (!is_numeric($target)) {
throw new InvalidArgumentException('第二个参数必须是数字');
}
$this->nums = $nums;
$this->target = $target;
}
/**
* 方法一:使用 PHP 内置函数搜索目标值
* @return int|false 返回目标值的索引,未找到返回 false
*/
public function searchArrayValue1()
{
return array_search($this->target, $this->nums);
}
/**
* 方法二:循环查找目标值
* @return int|false 返回目标值的索引,未找到返回 false
*/
public function searchArrayValue2()
{
foreach ($this->nums as $key => $val) {
if ($val == $this->target) {
return $key;
}
}
return false;
}
/**
* 方法三:使用二分查找
* @return int|false 返回目标值的索引,未找到返回 false
*/
public function searchArrayValue3()
{
$left = 0;
$right = count($this->nums) - 1;
while ($left <= $right) {
$mid = floor(($left + $right) / 2);
if ($this->nums[$mid] == $this->target) {
return $mid;
}
if ($this->nums[$left] <= $this->nums[$mid]) {
if ($this->target >= $this->nums[$left] && $this->target < $this->nums[$mid]) {
$right = $mid - 1;
} else {
$left = $mid + 1;
}
} else {
if ($this->target > $this->nums[$mid] && $this->target <= $this->nums[$right]) {
$right = $mid - 1;
} else {
$left = $mid + 1;
}
}
}
return false;
}
}
try {
$value = 0;
$index = new TitleOne([4, 5, 6, 7, 0, 1, 2], $value);
$res1 = $index->searchArrayValue1();
echo "方法一搜索元素 $value 结果:";
var_dump($res1);
$res2 = $index->searchArrayValue2();
echo "方法二搜索元素 $value 结果:";
var_dump($res2);
$res3 = $index->searchArrayValue3();
echo "方法三搜索元素 $value 结果:";
var_dump($res3);
} catch (InvalidArgumentException $e) {
echo "错误:" . $e->getMessage();
}
方法一搜索元素 0 结果:int(4)
方法二搜索元素 0 结果:int(4)
方法三搜索元素 0 结果:float(4)
评 论