Search for a Range

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].

很早之前就做的这道题,然而不明就理,这道题其实思路很简单,找到该元素出现的第一个位置和最后一个位置,两次二分。但是这两次在mid元素等于target时的操作不一样,寻找左元素时,则end = mid。右边界时start = end。代码如下:

class Solution(object):
    def searchRange(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        if not nums:
            return [-1,-1]
        l = 0
        r = len(nums)-1
        while l+1 < r: #find left
            mid = l + (r-l)/2
            if nums[mid] == target:
                r = mid 
            elif nums[mid] > target:
                r = mid
            else:
                l = mid 
        if nums[l]==target:
            left = l
        elif nums[r]==target:
            left = r
        else:
            left = -1
        l = 0
        r = len(nums)-1
        while l+1 < r: #find the right 
            mid = l+(r-l)/2
            if nums[mid] == target:
                l = mid
            elif nums[mid] > target:
                r = mid
            else:
                l = mid 
        if nums[r]==target:
            right = r
        elif nums[l] == target:
            right = l
        else:
            right = -1
        return [left,right]

 

posted on 2016-05-14 21:54  Sheryl Wang  阅读(126)  评论(0编辑  收藏  举报

导航