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

Search for a Range

时间:2016-05-14 23:03:01      阅读:171      评论:0      收藏:0      [点我收藏+]

标签:

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]

 

Search for a Range

标签:

原文地址:http://www.cnblogs.com/sherylwang/p/5493615.html

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