34. Find First and Last Position of Element in Sorted Array

#用二分查找法
class
Solution(object): def searchRange(self, nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ first = 0 last = len(nums) - 1 found = False results = [-1, -1] if nums == []: return results if target < nums[0] or target > nums[last]: return results while first <= last and not found: mid = (first + last) // 2 #找到了,分别继续向前,向后查找,直到找到第一个和最后一个target if target == nums[mid]: low = mid high = mid while low >= 0 and nums[low] == target: low -= 1 while high <= len(nums) - 1 and nums[high] == target: high += 1 found = True else: if target < nums[mid]: last = mid - 1 else: first = mid + 1 if found: return [low+1, high-1] else: return results
原文地址:https://www.cnblogs.com/boluo007/p/12295796.html