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

2026-03-11 16:15 By "Powerless" 16 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

  • PHP没你想的那么差
    Posted on 2021-12-17 15:40
  • Mysql联合索引的最左前缀匹配原则
    Posted on 2018-08-25 15:00
  • 2016年云计算热词
    Posted on 2019-06-12 17:53
  • 分布式架构之「 数据分布」
    Posted on 2019-11-14 10:00
  • 巧用CAS解决数据一致性问题
    Posted on 2019-03-07 11:55
  • PHP扩展ImageMagick安装
    Posted on 2022-11-11 11:16
  • 通过信鸽来解释HTTPS
    Posted on 2018-10-22 13:56
  • HTTP和HTTPS的区别
    Posted on 2020-08-10 23:00