代码随想录算法训练营第一天| 704. 二分查找、27. 移除元素
704. Binary Search
Given an array of integers nums which is sorted in ascending order, and an integer target, write a function to search target in nums. If target exists, then return its index. Otherwise, return -1.
Example:
Input: nums = [-1,0,3,5,9,12], target = 9
Output: 4
Explanation: 9 exists in nums and its index is 4
- Idea:** mid -> left/right
Sol1: 左闭右闭
class Solution:
def search(self, nums: List[int], target: int) -> int:
left, right = 0, len(nums) - 1 #左闭右闭
while left <= right: #"<="
mid = left + (right - left) // 2 #防溢出
if nums[mid] > target:
right = mid - 1 #"mid-1"右闭,当前值已排除
elif nums[mid] < target:
left = mid + 1 #left always "mid+1"
else:
return mid
return -1
Sol2: 左闭右开
class Solution:
def search(self, nums: List[int], target: int) -> int:
left, right = 0, len(nums) #左闭右开
while left < right: #"<",right no sense
mid = left + (right - left) // 2 #防溢出
if nums[mid] > target:
right = mid # 右开,当前值未排除
elif nums[mid] < target:
left = mid + 1 #左闭
else:
return mid
return -1
- Complexity: Time O(logn); Space O(1)
====================
27. Remove Element
Given an integer array nums and an integer val, remove all occurrences of val in nums in-place. The order of the elements may be changed. Then return the number of elements in nums which are not equal to val.
Example:
Input: nums = [3,2,2,3], val = 3
Output: 2, nums = [2,2,_,_]
Explanation: Your function should return k = 2, with the first two elements of nums being 2.
It does not matter what you leave beyond the returned k (hence they are underscores).
Sol1: Brute force
class Solution: #bruteforce
def removeElement(self, nums: List[int], val: int) -> int:
i,N=0,len(nums)
while i<N:# 不用for loop
if nums[i] == val:
for j in range(i,N-1):
nums[j]=nums[j+1]
#nums[-1]="_"
N-=1
else:
i+=1
return N
-
Note: 不用for loop, 因为i 不是每个loop都+1。在nums[i] == val时后面的数前移,当前位变化,需要重新判断,所以i不+1 。
-
Complexity. Time O(n^2); Space O(1)
Sol2: Two Pointers 快慢指针
class Solution: #two pointers (fast slow pointers)
def removeElement(self, nums:List[int],val:int) -> int:
slow,fast,N = 0,0,len(nums)
while fast<N:
if nums[fast] !=val:
nums[slow]=nums[fast]
slow+=1
fast+=1
return slow
-
Note: fast 遍历数组,slow记录nums[fast]!=val的值
-
Complexity. Time O(n); Space O(1)