Leetcode: Search for a Range


Get idea from here


Question

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


Analysis

Since the complexity is required to be O(log n), it is highly possible that binary search is needed. In the standard binary search, we will stop while finding the right element. In this problem, we have to keep searching its left most one and right most one.

Another thing should be noticed is that maybe this element is on the boundary or its left and right part has no the same element. We have to consider it using if-else.

We add a new parameter LorR, meaning it will keep searching left(right) most target value when finding the target in the mid.


Solution

class Solution:
    # @param {integer[]} nums
    # @param {integer} target
    # @return {integer[]}
    def searchRange(self, nums, target):
        if len(nums)==0 or target==None:
            return [-1, -1]

        result = [-1,-1]
        result[0] = self.search(nums, target, 0, len(nums)-1, 0)
        result[1] = self.search(nums, target, 0, len(nums)-1, 1)
        return result

    # LorR: 0(left), 1(right)
    def search(self, nums, target, left, right, LorR):
        if left>right:
            return -1

        mid = (left + right)/2
        if target<nums[mid]:
            return self.search(nums,target,left, mid-1, LorR)
        elif nums[mid]<target:
            return self.search(nums,target,mid+1,right, LorR)
        else:
            if LorR==0:
                if mid==0 or nums[mid-1]<nums[mid]:
                    return mid
                else:
                    return self.search(nums,target,left,mid-1,0)
            elif LorR==1:
                if mid==len(nums)-1 or nums[mid]<nums[mid+1]:
                    return mid
                else:
                    return self.search(nums,target,mid+1,right,1)


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值