1. Binary Search (Leetcode Number: 39)
Runtime complexity could be reduced by splitting the list into "equal" parts and comparing the middle value with the target value.
class Solution:
def search(self, nums: List[int], target: int) -> int:
left = 0
right = len(nums) - 1
while left <= right:
mid = left + (right - left) // 2
if nums[mid] > target:
right = mid - 1
elif nums[mid] < target:
left = mid + 1
else:
return mid
return -1
2. Remove Element (Leetcode Number: 27)
Appy two pointers slow and fast, slow pointer is used to store the values that are not equal to the given val, fast pointer goes through the list and marks all the qualified elements
class Solution:
def removeElement(self, nums: List[int], val: int) -> int:
slow = 0
fast = 0
while fast <= len(nums) - 1:
if nums[fast] != val:
nums[slow] = nums[fast]
slow += 1
fast += 1
return slow