PHP练习-搜索旋转排序数组

2026-03-11 16:15 By "Powerless" 15 0 0

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)

评 论

View in WeChat

Others Discussion

  • 初识七层、五层、四层网络协议
    Posted on 2021-04-09 16:52
  • 投票通过,PHP 8 确认引入 Union Types 2.0
    Posted on 2019-11-18 22:22
  • Linux工具 - NM目标文件格式分析
    Posted on 2019-04-24 10:29
  • PHP扩展安装
    Posted on 2019-06-24 11:28
  • Redis各种数据类型的使用场景举例分析【三】
    Posted on 2018-11-22 17:00
  • ACID原则
    Posted on 2020-12-17 16:36
  • PHP7不兼容性
    Posted on 2018-03-07 15:59
  • MySQL分组
    Posted on 2019-11-18 14:00