Merge pull request #2480 from alfie-chen/master
Update 0035.搜索插入位置 - 添加Python3 第二種二分法 - 左闭右开
This commit is contained in:
commit
54579e956d
|
|
@ -332,6 +332,7 @@ impl Solution {
|
||||||
### Python
|
### Python
|
||||||
|
|
||||||
```python
|
```python
|
||||||
|
# 第一种二分法: [left, right]左闭右闭区间
|
||||||
class Solution:
|
class Solution:
|
||||||
def searchInsert(self, nums: List[int], target: int) -> int:
|
def searchInsert(self, nums: List[int], target: int) -> int:
|
||||||
left, right = 0, len(nums) - 1
|
left, right = 0, len(nums) - 1
|
||||||
|
|
@ -348,6 +349,26 @@ class Solution:
|
||||||
return right + 1
|
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
|
### JavaScript
|
||||||
|
|
||||||
```js
|
```js
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue