代码随想录算法训练营day01| 704. 二分查找、27. 移除元素

704. 二分查找

题目链接

左闭右闭写法

class Solution:
    def search(self, nums: List[int], target: int) -> int:
     left = 0
     right = len(nums)-1
     while left <= right:
         mid = (right-left)//2 + left
         if nums[mid]  target:
             right = mid - 1
         else:
             return mid
     return -1                

middle = left + (right -left)//2 和(left+right)//2数学意义上没差别,但是为了考虑整数溢出,会采用left + (right-left)//2 的写法

左闭右开写法

class Solution:
    def search(self, nums: List[int], target: int) -> int:
     left = 0
     right = len(nums)
     while left < right:
         mid = (right-left)//2 + left
         if nums[mid]  target:
             right = mid 
         else:
             return mid
     return -1                

27. 移除元素

题目链接


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


注意:a 不能等于len(nums)

你可能感兴趣的:(leetcode,leetcode)