Search for a Range

Given a sorted array of n integers, find the starting and ending position of a given target value.

If the target is not found in the array, return [-1, -1].

Example

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

return [3, 4].

Solution

首先得出第一个索引的值, 然后在通过二分法得出最后一个索引的值,返回数组结果。

首先 是如何求出重复值的第一个索引值,与最后一个索引值,一步是不能求出第一个最后一个重复值,因为我们的最后切割后只留下了一个两个月元素的window, 但是重复值有可能是大于两个元素的,所以必须要写两步二分运算. 如果第一个二分法找不到元素就没有必要继续找了直接返回.

Make the mistake and take 1 hour: 二分法写的时候忘记了除2 ,结果导致益出错误: mid = (start + end)

class Solution:
    """
    @param A : a list of integers
    @param target : an integer to be searched
    @return : a list of length 2, [index1, index2]
    """
    def searchRange(self, A, target):
        if len(A) == 0:
            return [-1, -1]

        start, end = 0, len(A) - 1
        while start + 1 < end:
            mid = (start + end) / 2
            if A[mid] < target:
                start = mid
            else:
                end = mid

        if A[start] == target:
            leftBound = start
        elif A[end] == target:
            leftBound = end
        else:
            return [-1, -1]

        start, end = leftBound, len(A) - 1
        while start + 1 < end:
            mid = (start + end) / 2
            if A[mid] <= target:
                start = mid
            else:
                end = mid
        if A[end] == target:
            rightBound = end
        else:
            rightBound = start
        return [leftBound, rightBound]

Last updated

Was this helpful?