l704 二分查找:
class Solution:
def search(self, nums: List[int], target: int) -> int:
length = len(nums)
high = length-1
low = 0
while low <= high:
mid = (low+high)//2
if nums[mid] < target:
low = mid+1
elif nums[mid] > target:
high = mid-1
elif nums[mid] == target:
return mid
return -1
要点:low <= high中,等号必须要有。否则在low = high的特殊情况下,会漏掉正确的结果。
l27 移除元素(后的长度):
难点在于:列表中,删除元素时,只能一个个向前覆盖。
解决方法:快慢指针
class Solution:
def removeElement(self, nums: List[int], val: int) -> int:
fast = 0
slow = 0
length = len(nums)
while fast <= length - 1:
if nums[fast] != val:
nums[slow] = nums[fast]
slow += 1
fast += 1
print(nums[:slow])
return slow
可以注意一下while的写法, 相当于这么写:
while fast <= length - 1:
if nums[fast] != val:
nums[slow] = nums[fast]
slow += 1
fast += 1
else:
fast += 1