• LeetCode Medium: 34. Search for a Range


    一、题目

    Given an array of integers nums sorted in ascending order, 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].

    Example 1:

    Input: nums = [5,7,7,8,8,10], target = 8
    Output: [3,4]

    Example 2:

    Input: nums = [5,7,7,8,8,10], target = 6
    Output: [-1,-1]
    题目意思就是给定一个升序的数组和一个target,找出target在此数组中的起始位置和终止位置。
    二、思路
    此题是easy题二分法的变种,基本思路一样,不同的是如果target == nums [ mid ]时,需要往两边扩展进行搜索,看是否有和 target 相同的数字。
    三、代码
     
    #coding:utf-8
    class Solution:
        def searchRange(self, nums, target):
            """
            :type nums: List[int]
            :type target: int
            :rtype: List[int]
            """
            left = 0
            right = len(nums)-1
            result = [-1,-1]
            while left <= right:
                mid = (left + right)//2
                if nums[mid] > target:
                    right = mid - 1
                elif nums[mid] < target:
                    left = mid + 1
                else:
                    result[0] = mid
                    result[1] = mid
                    i = mid - 1
                    while nums[i] == target and i >= 0:
                        result[0] = i
                        i-=1
                    i = mid + 1
                    while nums[i] == target and i < len(nums):
                        result[1] = i
                        i+=1
                    break
    
            print(result)
            return result
    if __name__ == '__main__':
        nums = [5,7,7,8,8,10]
        ss = Solution()
        ss.searchRange(nums,8)
    

      

    既然无论如何时间都会过去,为什么不选择做些有意义的事情呢
  • 相关阅读:
    [自用] 数论和组合计数类数学相关(定理&证明&板子)
    OI回忆录?
    [UOJ310] 黎明前的巧克力
    [总结] 后缀自动机学习笔记
    [总结] 动态点分治学习笔记
    [HEOI2018] 秘密袭击coat
    [51nod1355] 斐波那契的最小公倍数
    [SRM601] WinterAndSnowmen
    [总结] 二项式反演学习笔记
    [Luogu4705] 玩游戏
  • 原文地址:https://www.cnblogs.com/xiaodongsuibi/p/8975655.html
Copyright © 2020-2023  润新知