代码随想录算法训练营20期|第一天|数组part01|数组理论基础,704. 二分查找,27. 移除元素

数组理论基础,

704. 二分查找,

左闭右闭法:判断边界的时候把边界带入进去试试

Time: O(logn)

Space: O(1)

class Solution:
    def search(self, nums: List[int], target: int) -> int:
        left = 0
        right = len(nums) - 1

        while left <= right:
            mid = (left + right) // 2
            if nums[mid] < target:
                left = mid + 1
            elif nums[mid] > target:
                right = mid - 1
            else:
                return mid
        return -1

27. 移除元素  

双指针:slow, fast

用fast来移除

Time: O(n) 

Space (O(1))

class Solution:
    def removeElement(self, nums: List[int], val: int) -> int:
        slow = 0
        fast = 0
        size = len(nums)
        while fast < size:
            if nums[fast] != val:
                nums[slow] = nums[fast]
                slow += 1
            fast += 1
        return slow
        

你可能感兴趣的:(代码随想录二刷,算法,数据结构)