034 Search for a Range

034 Search for a Range

二分搜索, 搜左右部分稍微有些不同 需要注意

class Solution:
    # @param {integer[]} nums
    # @param {integer} target
    # @return {integer[]}
    def searchRange(self, nums, target):
        left = self.findIndex(nums, target, "left", 0, len(nums)-1)
        if left == -1:
            return [-1,-1]
        right = self.findIndex(nums, target, "right", left, len(nums)-1)
        return [left, right]
        
    def findIndex(self, nums, target, model, left, right):
        if left > right:
                return -1
        if left == right:
            if nums[left] == target:
                return left
            else:
                return -1
        if model == "left":
            mid = (left + right) / 2
        else:
            mid = (left + right + 1) / 2
        if nums[mid] > target:
            right = mid - 1
        elif nums[mid] < target:
            left = mid + 1
        else:
            if model == "left":
                right = mid
            else:
                left = mid
        return self.findIndex(nums, target, model, left, right)

 

posted @ 2015-07-17 12:11  dapanshe  阅读(118)  评论(0编辑  收藏  举报