From 20216736e5daf5828bf45d1d04e238057074b7fa Mon Sep 17 00:00:00 2001 From: alfiechen Date: Fri, 15 Mar 2024 23:26:45 +0800 Subject: [PATCH] =?UTF-8?q?Update=200035.=E6=90=9C=E7=B4=A2=E6=8F=92?= =?UTF-8?q?=E5=85=A5=E4=BD=8D=E7=BD=AE=20-=20=E6=B7=BB=E5=8A=A0Python3=20?= =?UTF-8?q?=E7=AC=AC=E4=BA=8C=E7=A8=AE=E4=BA=8C=E5=88=86=E6=B3=95=20-=20?= =?UTF-8?q?=E5=B7=A6=E9=97=AD=E5=8F=B3=E5=BC=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0035.搜索插入位置.md | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) 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