Leetcode做题日记:34. 在排序数组中查找元素的第一个和最后一个位置(PYTHON)

给定一个按照升序排列的整数数组 nums,和一个目标值 target。找出给定目标值在数组中的开始位置和结束位置。
你的算法时间复杂度必须是 O(log n) 级别。
如果数组中不存在目标值,返回 [-1, -1]。

示例 1:

输入: nums = [5,7,7,8,8,10], target = 8
输出: [3,4]

示例 2:

输入: nums = [5,7,7,8,8,10], target = 6
输出: [-1,-1]

第一次的代码,暴力遍历,32ms

	if target not in nums:
            return[-1,-1]
        i=0
        while True:
            if nums[i]==target:
                if i==len(nums)-1:
                    return[i,i]
                j=1
                while True:
                    if i+j==len(nums):
                        return[i,i+j-1]
                    if nums[i+j]==target:
                        j=j+1
                    else:
                        return [i,i+j-1]     
            i=i+1

第二次,从两端找到左右,依然是32ms:

	if target not in nums:
            return[-1,-1]
        i=0
        while nums[i]!=target:
            i=i+1
        j=0
        while nums[-1-j]!=target:
            j=j+1
        return [i,len(nums)-1-j]

最后,我的二分查找不知道哪里错了,总是超时

	if target not in nums:
            return[-1,-1]
        st=0
        L=len(nums)
        en=L-1
        while st<=en:
            two=(st+en)//2
            if nums[two]<target:
                en=two
            elif nums[two]>target:
                en=two
            elif nums[two]==target:
                st1=two
                en1=two
                i=1
                j=1
                while st-j>=0 and nums[st-j]==target:
                    st=st-1
                    j=j+1
                while en+i<L and nums[en+i]==target:
                    en=en+1
                    i=i+1
                return[st,en]

猜你喜欢

转载自blog.csdn.net/weixin_44033136/article/details/85543371