自己刷题总是容易松懈,于是看到了代码随想录的算法训练营,打算跟着计划刷题。写博客能够起到一个监督的作用嘻嘻。
Q1: 704: Binary Search
class Solution:
def search(self, nums: List[int], target: int) -> int:
s, t = 0, len(nums)
while s < t:
mid = (s+t)//2
if nums[mid] == target:
return mid
elif nums[mid] < target:
s = mid + 1
else:
t = mid
return -1
用时2min;区间左开右闭,其他没有要注意的点了。
Q2: 24: Remove Element
class Solution:
def removeElement(self, nums: List[int], val: int) -> int:
i, j = 0, 0
while j < len(nums):
if nums[j] != val:
nums[i], nums[j] = nums[j], nums[i]
i += 1
j += 1
return i
用时10min
双指针;一般双指针分为两种,一种是一快一慢,像这道题,另外一种是首尾双指针。
希望能够坚持!