码迷,mamicode.com
首页 > 其他好文 > 详细

034 Search for a Range

时间:2015-07-17 13:39:08      阅读:99      评论:0      收藏:0      [点我收藏+]

标签:

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)

 

034 Search for a Range

标签:

原文地址:http://www.cnblogs.com/dapanshe/p/4654084.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!