My accepted solution with explanation


  • 0
    V
        def searchRange(self, nums, target):
            left = self.findLooseUpperBound(nums, target)
            right = self.findLooseLowerBound(nums, left, target)
            
            return [left, right]
        
        def findLooseLowerBound(self, nums, l, target):
            r = len(nums) - 1
            
            while l < r:
                mid = l + (r - l + 1) / 2
                
                if nums[mid] <= target:
                    l = mid
                else:
                    r = mid - 1
            
            return r if nums[r] == target else -1
        
        def findLooseUpperBound(self, nums, target):
            l, r = 0, len(nums) - 1
            
            while l < r:
                mid = l + (r - l) / 2
                
                if nums[mid] >= target:
                    r = mid
                else:
                    l = mid + 1
            
            return l if nums[l] == target else -1
    

    I use two functions(findLooseUpperBound() and findLooseLowerBound()) to find the first element >= target from left and the first element <= target from right, which are start and end of the range respectively.

    Learn more


  • 0
    A

    Nice solution!
    Thank you for sharing.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.