diff --git a/problems/0035.搜索插入位置.md b/problems/0035.搜索插入位置.md index 9a770703..8a8f9706 100644 --- a/problems/0035.搜索插入位置.md +++ b/problems/0035.搜索插入位置.md @@ -318,6 +318,31 @@ func searchInsert(_ nums: [Int], _ target: Int) -> Int { ``` +### PHP + +```php +// 二分法(1):[左闭右闭] +function searchInsert($nums, $target) +{ + $n = count($nums); + $l = 0; + $r = $n - 1; + while ($l <= $r) { + $mid = floor(($l + $r) / 2); + if ($nums[$mid] > $target) { + // 下次搜索在左区间:[$l,$mid-1] + $r = $mid - 1; + } else if ($nums[$mid] < $target) { + // 下次搜索在右区间:[$mid+1,$r] + $l = $mid + 1; + } else { + // 命中返回 + return $mid; + } + } + return $r + 1; +} +``` -----------------------