【力扣100】34.在排序数组中查找元素的第一个和最后一个位置 || 时间复杂度大小

添加链接描述

class Solution:
    def searchRange(self, nums: List[int], target: int) -> List[int]:
        n=len(nums)
        i,j=0,n-1
        if not n:
            return [-1,-1]
        while i<=j:
            mid=i+(j-i)//2
            if target<nums[mid]:
                j=mid-1
            elif target>nums[mid]:
                i=mid +1
            else:
                x,y=mid,mid
                while x-1>=0 and nums[x-1]==target:
                    x=x-1
                while y+1<=n-1 and nums[y+1]==target:
                    y=y+1
                return [x,y]
        return [-1,-1]

思路:

  1. 使用二分查找
  2. 找到对应位置后,向左向右寻找相同值


时间复杂度大小:

O(1) < O(logn) < O(n) < O(nlogn) < O(n^2) < O(n^3) < O(2^n)

解法二:把解法一的while拿出来分开写

class Solution:
    def searchRange(self, nums: List[int], target: int) -> List[int]:
        def searchLeft(nums, target):
            # 左边界需要满足两个条件:
            # 1. 他的值为target
            # 2. 他的左边元素小于他,或者他的下标为0
            left, right = 0, len(nums)-1
            while left <= right:
                mid = (right-left)//2 + left
                if nums[mid] == target:
                    if mid == 0 or nums[mid-1] < target:
                        return mid
                    else:
                        right = mid - 1
                elif nums[mid] > target:
                    right = mid - 1
                else:
                    left = mid + 1
            return -1
        
        def searchRight(nums, target):
            # 右边界需要满足两个条件:
            # 1. 他的值为target
            # 2. 他的右边元素大于他,或者他的下标为len(nums)-1
            left, right = 0, len(nums)-1
            while left <= right:
                mid = (right-left)//2 + left
                if nums[mid] == target:
                    if mid == len(nums)-1 or nums[mid+1] > target:
                        return mid
                    else:
                        left = mid + 1
                elif nums[mid] > target:
                    right = mid - 1
                else:
                    left = mid + 1
            return -1

        return [searchLeft(nums, target), searchRight(nums, target)]

你可能感兴趣的:(leetcode,算法,职场和发展)