[BinarySearch]034 Find First and Last Position of Element in Sorted Array

  • 分类:BinarySearch

  • 考察知识点:BinarySearch

  • 最优解时间复杂度:O(logn)

  • 最优解空间复杂度:O(1)

34. Find First and Last Position of Element in Sorted Array

Given an array of integers nums sorted in ascending order, find the starting and ending position of a given target value.

Your algorithm's runtime complexity must be in the order of O(log n).

If the target is not found in the array, return [-1, -1].

Example 1:

Input: nums = [5,7,7,8,8,10], target = 8
Output: [3,4]

Example 2:

Input: nums = [5,7,7,8,8,10], target = 6
Output: [-1,-1]

代码:

BinarySearch方法:

class Solution:
    def searchRange(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        # 边界条件
        if len(nums)==0 or targetnums[len(nums)-1]:
            return [-1,-1]
        start=self.findStart(nums,target)
        if start==-1:
            return [-1,-1]

        end=self.findEnd(nums,target,start)
        return [start,end]

    def findStart(self,nums,target):
        start=0
        end=len(nums)-1
        while(end-start>1):
            mid=(end-start)//2+start
            if nums[mid]1):
            mid=(end-start)//2+start
            if nums[mid]>target:
                end=mid
            else:
                start=mid
        if nums[end]==target:
            return end
        if nums[start]==target:
            return start

讨论:

1.排序的,然后找数字,一看到这两个条件,那么肯定是用binary search!切记切记
2.大佬的方法有些重复,但是也还可以,就这样吧

加油!

你可能感兴趣的:([BinarySearch]034 Find First and Last Position of Element in Sorted Array)