LeetCode #34 Find First and Last Position of Element in Sorted Array

题目

Find First and Last Position of Element in Sorted Array


解题思路

数组查找问题,考虑采用二分查找降低时间复杂度,找到target后只需分别向前向后找到start和end即可。


代码

class Solution:
    def searchRange(self, nums: List[int], target: int) -> List[int]:
        low, start = 0, -1
        high, end = len(nums) - 1, -1
        
        while low <= high:
            mid = (low + high) // 2
            if target < nums[mid]:
                high = mid - 1
            elif target > nums[mid]:
                low = mid + 1
            else:
                start = mid
                while start - 1 >= 0 and nums[start-1] == nums[mid]:
                    start -= 1
                end = mid
                while end + 1 <= len(nums) - 1 and nums[end+1] == nums[mid]:
                    end += 1
                break
        
        return [start, end]
posted @ 2020-10-12 09:23  老鼠司令  阅读(53)  评论(0)    收藏  举报