704. 二分查找
- 左闭右闭
class Solution(object): def search(self, nums, target): left = 0 right = len(nums)-1 !包括right while left <= right: !等号有效 mid = (left+right) // 2 if nums[mid] == target: return mid if nums[mid] < target: left = mid + 1 else: right = mid - 1 !包括right -> mid-1 return -1
- 左闭右开
class Solution(object): def search(self, nums, target): left = 0 right = len(nums) !不包括right while left < right: !等号无效 mid = (left+right) // 2 if nums[mid] == target: return mid if nums[mid] < target: left = mid + 1 else: right = mid !不包括right -> mid return -1
- 时间复杂度:O(log n)
- 空间复杂度:O(1)
27.移除元素
1. 暴力解法
class Solution(object):
def removeElement(self, nums, val):
k = len(nums)
i = 0
while i < k:
if nums[i] == val:
nums[i] = nums[k - 1]
k -= 1
else:
i += 1
return k
- 时间复杂度:O(n^2)
- 空间复杂度:O(1)
2. 双指针
class Solution(object):
def removeElement(self, nums, val):
i = j = 0
while j < len(nums):
if nums[j] != val:
nums[i] = nums[j]
i += 1
j += 1
return i
- 时间复杂度:O(n)
- 空间复杂度:O(1)