704. 二分查找 Binary Search
目标值先跟mid比较,然后调整区间
适用范围:有序数组,无重复元素
注意循环不变量:左闭右闭/左闭右开/...
class Solution:
def search(self, nums: List[int], target: int) -> int:
left = 0
right = len(nums)-1
while left<=right:
mid = (left+right)//2
if target<nums[mid]:
right = mid-1
elif target>nums[mid]:
left=mid+1
else:
return mid
return -1
27. 移除元素
快慢指针
快指针:符合要求的元素的下标
慢指针:新数组的元素的下标
O(n*2) -> O(n)
class Solution:
def removeElement(self, nums: List[int], val: int) -> int:
# fast=0
slow=0
for fast in range(len(nums)):
if nums[fast] != val:
nums[slow] = nums[fast]
slow += 1
return slow