https://leetcode.cn/problems/find-first-and-last-position-of-element-in-sorted-array/
# 解法:
# 1、首先,在 nums 数组中二分查找 target;
# 2、如果二分查找成功,则将nums中查找的值为 target 的索引值 mid 依次执行 -1 和 +1 操作分别赋值给左右边界 left 和 right。然后,通过循环滑动左右边界 left-=1 和 right+=1 ,来找到符合题意的边界,并将最终的左右边界保存在数组count中,最终返回count。
# 3、如果二分查找失败,则返回[-1,-1]
class Solution:
def searchRange(self, nums: List[int], target: int) -> List[int]:
left, right = 0, len(nums)-1
while left<=right:
mid = (left+right)//2
count = []#记录初始位置和最后位置的数组
if nums[mid]==target:
left = mid-1
right=mid+1
while left>=0 and nums[left]==nums[mid]:
left-=1
count.append(left+1)
while right<=len(nums)-1 and nums[right]==nums[mid]:
right += 1
count.append(right-1)
return count
elif nums[mid]>target:
right = mid-1
else:
left = mid+1
return [-1,-1]