Binary search and stupid way to find the range. Python solution


  • 0
    H
    class Solution(object):
    def searchRange(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        low = 0
        high = len(nums)-1
        flag = 0
        while (low <= high):
            mid = (low+high)/2
            if nums[mid] < target:
                low = mid + 1
            elif nums[mid] > target:
                high = mid - 1
            else:
                flag = 1
                break
        if flag == 0:
            return [-1,-1]
        else:
            split,split2 = mid,mid
            start,stop=-1,-1
            while(split>=0):
                if nums[split] == target:
                    start = split
                else:
                    break
                split = split - 1
            while(split2 <= len(nums)-1):
                if nums[split2] == target:
                    stop = split2
                else:
                    break
                split2 = split2 + 1
            return [start,stop]

Log in to reply
 

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