leetcode (18) - find elements in the array to sort

Nums Given an array of integers arranged in ascending order, according to the target and one target value. Identify a given target start and end positions in the array.

Your time complexity of the algorithm must be O (log n) level.

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

Source: stay button (LeetCode)
link: https://leetcode-cn.com/problems/find-first-and-last-position-of-element-in-sorted-array
copyrighted by deduction from all networks. Commercial reprint please contact the authorized official, non-commercial reprint please indicate the source.

My solution

Binary search, then a recursive binary search [head, mid-1], [mid + 1, tail], the result masterpiece [right_1, right_2], mid, maximum legal [left_1, left_2] results in

class Solution:
    def searchRange(self, nums, target: int):
        if len(nums)==0:return [-1,-1]
        head = 0
        tail = len(nums)-1
        find = None
        while head<=tail:
            mid = (head+tail)//2
            if nums[mid]<target:head = mid+1
            elif nums[mid]>target:tail = mid-1
            else:
                find = mid
                break
        if find is None:return [-1,-1]
        ans = [mid,mid]
        left = self.searchRange(nums[head:mid],target)
        ans[0] = left[0]+head if left[0]>0 else ans[0]
        right = self.searchRange(nums[mid+1:tail+1],target)
        ans[1] = right[1]+mid+1 if right[0]>0 else ans[1]
        return ans

Official explanations

A half to find the right maximum, a half left to find

Guess you like

Origin www.cnblogs.com/Lzqayx/p/12157866.html