26. 删除有序数组中的重复项
双指针
class Solution:
def removeDuplicates(self, nums: List[int]) -> int:
n = len(nums)
j = 0
for i in range(n):
if nums[i] != nums[j]:
j += 1
nums[j] = nums[i]
return j + 1
27. 移除元素
class Solution:
def removeElement(self, nums: List[int], val: int) -> int:
n = len(nums)
j = 0
for i in range(n):
if nums[i] != val:
nums[j] = nums[i]
j += 1
return j
或者:
class Solution:
def removeElement(self, nums: List[int], val: int) -> int:
a = 0
b = 0
while a < len(nums):
if nums[a] != val:
nums[b] = nums[a]
b += 1
a += 1
return b
35. 搜索插入位置
class Solution:
def searchInsert(self, nums: List[int], target: int) -> int:
j = 0
for i in range(len(nums)):
if nums[i] == target:
j = i
elif nums[i] < target:
j = i+1
return j
二分法
更快
class Solution:
def searchInsert(self, nums: List[int], target: int) -> int:
n = len(nums)
left = 0
right = n
while left < right:
mid = int((right + left)/2)
if nums[mid] < target:
left = mid +1
else:
right = mid
return left