Leetcode 034 搜索范围 思路详解 python

本人一直在努力地积累Leetcode上用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]

思路:

首先要明确,这道题让我们使用logn,而且数组是经过排序的。这样的话很明显我们要使用2分的思想。


Step1:先用二分找到一个值

Step2:如果没找到,直接return[-1,-1],找到了就以此点向数组2边扩张,知道到达相同值的边界。


class Solution:
    def searchRange(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        l = 0 
        r = len(nums)-1
        
        if len(nums) == 0:
            return [-1, -1]
        #先用2分去找这个target的任意一个index
        while l <= r:
            mid = (l + r)//2
            if nums[mid] > target:
                r = mid-1
            elif nums[mid] < target:
                l = mid+1
            else:
                start = mid
                end = mid
                break
        #判断找没找到
        if nums[mid] != target:
            return [-1, -1]
        #找到了向左扩
        while start - 1>=0 and nums[start] == nums[start-1]:
            start = start - 1
        #找到了向右扩
        while end + 1 <= len(nums) - 1 and nums[end] == nums[end+1]:
            end = end + 1
        return [start,end]



猜你喜欢

转载自blog.csdn.net/weixin_41958153/article/details/80868658