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)

  

既然无论如何时间都会过去,为什么不选择做些有意义的事情呢
原文地址:https://www.cnblogs.com/xiaodongsuibi/p/8975655.html