• 排序数组中查找目标原始的开始和结束索引


    # 给定一个按照升序排列的整数数组 nums,和一个目标值 target。找出给定目标值在数组中的开始位置和结束位置。 
    #
    # 如果数组中不存在目标值 target,返回 [-1, -1]。
    #
    # 进阶:
    #
    #
    # 你可以设计并实现时间复杂度为 O(log n) 的算法解决此问题吗?
    #
    #
    #
    #
    # 示例 1:
    #
    #
    # 输入:nums = [5,7,7,8,8,10], target = 8
    # 输出:[3,4]

    方法:二分法的变体

    # leetcode submit region begin(Prohibit modification and deletion)
    class Solution:
        def searchRange(self, nums: List[int], target: int) -> List[int]:
            left, right = 0, len(nums) - 1
            res = self.two_division(nums, target, left, right)
            return res
    
        def two_division(self, nums, target, left, right):
            while left <= right:
                mid = (left + right) // 2
                if nums[mid] == target:
                    start, end = mid, mid
                    while start - 1 >= 0 and nums[start - 1] == target:
                        start -= 1
                    while end + 1 < len(nums) and nums[end + 1] == target:
                        end += 1
                    return [start, end]
                elif nums[mid] < target:
                    left = mid + 1
                else:
                    right = mid - 1
            return [-1, -1]
    # leetcode submit region end(Prohibit modification and deletion)
    时刻记着自己要成为什么样的人!
  • 相关阅读:
    Python爬虫_分布式爬虫
    Python爬虫_selenium
    Python爬虫_scrapy框架
    Python爬虫_高性能爬取
    Python爬虫_三种数据解析方式
    Python爬虫_requests模块
    Django
    Python爬虫相关基础概念
    MySQL 多表结构的创建与分析
    mysql
  • 原文地址:https://www.cnblogs.com/demo-deng/p/14955124.html
Copyright © 2020-2023  润新知