leetcode-34-search for a range

本文介绍了一种在有序数组中查找指定目标值起始和结束位置的算法。该算法利用二分查找提高效率,确保运行时间复杂度为O(log n)。文中还提供了具体的Python实现案例。

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
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值