34. Search for a Range leetcode Python 2016 new season

Given a sorted array of integers, 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].

For example,
Given [5, 7, 7, 8, 8, 10] and target value 8,

return [3, 4].

1. do a binary search to check the position.

2. check both side until the number is no longer the target.

class Solution(object):
    def binSearch(self, nums, target):
        low = 0
        high = len(nums) - 1
        while True:
            if low > high:
                return -1
            mid = low + (high - low) / 2
            if nums[mid] < target:
                low = mid + 1
            elif nums[mid] > target:
                high = mid - 1
            else:
                return mid
    def searchRange(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        pos = self.binSearch(nums, target)
        if pos == -1:
            return [-1, -1]
        else:
            left, right = pos, pos
            while left >= 0 and nums[left] == target:
                left -= 1
            while right < len(nums) and nums[right] == target:
                right += 1
            return [left + 1, right - 1]
            
            
            
        


你可能感兴趣的:(34. Search for a Range leetcode Python 2016 new season)