leetcode-34-search for a range

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

题意:在一个有序数组中 查找某个target的范围,返回起始索引。
如果查找不到,返回[-1,-1]。要求算法复杂度logn。

直接二分查找到target的索引,然后往前后判断是否等于target。

class Solution(object):
    def searchRange(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        l,r=0,len(nums)-1
        t=-1
        a=[]
        if r==-1:return [-1,-1]
        while(l<=r):
            m=(l+r)/2
            if(nums[m]==target):
                t=m
                break
            if(nums[m]>target):r=m-1
            else:l=m+1
        if t==-1:return [-1,-1]
        while(m>=0):
            if(nums[m]!=target):
                break
            m=m-1
        a.append(m+1)
        while(t<=(len(nums)-1)):
            if(nums[t]!=target):
                break
            t=t+1
        a.append(t-1)
        return a
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值