mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-06 23:28:29 +08:00
Merge pull request #2480 from alfie-chen/master
Update 0035.搜索插入位置 - 添加Python3 第二種二分法 - 左闭右开
This commit is contained in:
@ -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
|
||||
|
Reference in New Issue
Block a user