diff --git a/problems/0035.搜索插入位置.md b/problems/0035.搜索插入位置.md index 80b7e40e..c969d730 100644 --- a/problems/0035.搜索插入位置.md +++ b/problems/0035.搜索插入位置.md @@ -332,6 +332,7 @@ impl Solution { ### Python ```python +# 第一种二分法: [left, right]左闭右闭区间 class Solution: def searchInsert(self, nums: List[int], target: int) -> int: left, right = 0, len(nums) - 1 @@ -348,6 +349,26 @@ class Solution: return right + 1 ``` +```python +# 第二种二分法: [left, right)左闭右开区间 +class Solution: + def searchInsert(self, nums: List[int], target: int) -> int: + left = 0 + right = len(nums) + + while (left < right): + middle = (left + right) // 2 + + if nums[middle] > target: + right = middle + elif nums[middle] < target: + left = middle + 1 + else: + return middle + + return right +``` + ### JavaScript ```js