704 二分查找
基础,属于复习啦
左闭右闭
class Solution(object):
def search(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
# 左闭右闭
left, right = 0, len(nums)-1
while left <= right:
mid = (left+right)//2
if nums[mid] == target:
return mid
elif nums[mid] > target:
right = mid - 1
else:
left = mid + 1
return -1
左闭右开
class Solution(object):
def search(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
# 左闭右开
left, right = 0, len(nums)
while left < right:
mid = (left + right) //2
if nums[mid] == target:
return mid
elif nums[mid] < target:
left = mid + 1
else:
right = mid
return -1
27 移除元素
第一次尝试——失败:
- 原地修改数组——>使用双指针
- 不在意顺序+新数组集中在数组前排位置——>交换不符合要求的到数组靠后位置,两个指针相向而行。
class Solution(object):
def removeElement(self, nums, val):
"""
:type nums: List[int]
:type val: int
:rtype: int
"""
if not nums or len(nums) == 0:
return 0
left, right = 0, len(nums) - 1
while nums[right] == val and right >= 0:
right -= 1
while left < right:
if nums[left] == val:
nums[left], nums[right] = nums[right], nums[left]
right -= 1
left += 1
return right + 1
存在问题:
如果需要排除的数字一开始就集中在前面,容易漏掉需要排除的数字。
e.g. nums =[2,2,3], val = 2 。正确输出:[3], 我的输出:[3,2]
第二次尝试——成功:
class Solution(object):
def removeElement(self, nums, val):
"""
:type nums: List[int]
:type val: int
:rtype: int
"""
if not nums or len(nums) == 0:
return 0
left, right = 0, len(nums) - 1
while nums[right] == val and right >= 0:
right -= 1
while left <= right:
if nums[right] == val:
right -= 1
continue
if nums[left] == val:
nums[left], nums[right] = nums[right], nums[left]
right -= 1
left += 1
return right + 1
普遍解法——快慢指针:
保原来数组顺序,更好理解,写法更简洁:
class Solution(object):
def removeElement(self, nums, val):
"""
:type nums: List[int]
:type val: int
:rtype: int
"""
if not nums or len(nums) == 0:
return 0
slow = 0
for fast in range(len(nums)):
if val != nums[fast]:
nums[slow] = nums[fast]
slow += 1
return slow