## 代码随想录Python：704. 二分查找，27. 移除元素

1、在进行二分查找过程中，区间的定义非常的重要。

• 左闭右闭
• 左闭右开

``````class Solution(object):
def search(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
left = 0
right = len(nums) - 1
# 左闭右闭
while left <= right:
middle = (left + right) / 2
if nums[middle] < target:
left = middle + 1
elif nums[middle] > target:
right = middle - 1
else:
return middle
return -1``````

``````class Solution(object):
def search(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
left = 0
right = len(nums) - 1
# 左闭右开
while left < right:
middle = (left + right) / 2
if nums[middle] < target:
left = middle + 1
elif nums[middle] > target:
right = middle
else:
return middle
return -1
``````

2、在数组中进行元素移除

``````class Solution(object):
def removeElement(self, nums, val):
"""
:type nums: List[int]
:type val: int
:rtype: int
"""
slow = 0
for fast in range(len(nums)):
if nums[fast] != val:
nums[slow] = nums[fast]
slow = slow + 1
return slow``````

### Guess you like

Origin blog.csdn.net/muyuejinxing/article/details/131447063
Recommended
Ranking
Daily