leetcode —— 34. 在排序数组中查找元素的第一个和最后一个位置

给定一个按照升序排列的整数数组 nums,和一个目标值 target。找出给定目标值在数组中的开始位置和结束位置。

你的算法时间复杂度必须是 O(log n) 级别。

如果数组中不存在目标值,返回 [-1, -1]。

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

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/find-first-and-last-position-of-element-in-sorted-array
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
————————————
解题思路:使用二分查找,找到最左边的target值,然后使用二分查找,找到最右边的target值。

Python代码:

class Solution:
    def searchRange(self, nums: List[int], target: int) -> List[int]:
        if not nums or target<nums[0] or target>nums[-1]:
            return [-1,-1]
        length = len(nums)
        begin = -1
        end = -1
        L = 0
        R = length-1
        while L<=R:  # 找到最左边的target的位置
            mid = (L+R)//2
            if nums[mid]<target:
                L = mid+1
            elif nums[mid]>=target:
                R = mid-1
        begin = L
        L = 0
        R = length-1
        while L<=R:  # 找到最右边的target位置
            mid = (L+R)//2
            if nums[mid]<=target:
                L = mid+1
            elif nums[mid]>target:
                R = mid-1
        end = R
        if begin>end:  # 如果begin的值在end的右边,则数组中没有target值
            return [-1,-1]
        return [begin,end]
发布了320 篇原创文章 · 获赞 21 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/qq_37388085/article/details/105313260