Sharing my accepted O(2logN) Python solution. It's quite redundant though.


  • 0
    X
    class Solution:
        # @param A, a list of integers
        # @param target, an integer to be searched
        # @return a list of length 2, [index1, index2]
        def searchRange(self, A, target):
            start = 0
            end = len(A)-1
            left = -1
            right = -1
            while start <= end:
                mid = (start+end) // 2
                if A[mid] < target:
                    start = mid+1
                elif A[mid] > target:
                    end = mid-1
                else: #A[mid] == target
                    left = mid
                    end = mid-1
            start = 0
            end = len(A)-1
            while start <= end:
                mid = (start+end)//2
                if A[mid] < target:
                    start = mid+1
                elif A[mid] > target:
                    end = mid-1
                else: #A[mid] == target
                    right = mid
                    start = mid+1
            return [left, right]

Log in to reply
 

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