Loading...

10-09 leeetcode 0034

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

题目

Given an array of integers nums sorted in non-decreasing order, find the starting and ending position of a given target value.

If target is not found in the array, return [-1, -1].

You must write an algorithm with O(log n) runtime complexity.

题解

二分查找到一个后,从中心向两边扩散,找到边界

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class Solution:
def searchRange(self, nums: list[int], target: int) -> List[int]:
index = -1
if not nums:
return [-1, -1]
start, end = 0, len(nums) - 1
while start <= end:
mid = start + (end - start) // 2
if nums[mid] == target:
index = mid
break
elif nums[mid] > target:
end = mid - 1
else:
start = mid + 1
if index == -1:
return [-1, -1]
left, right = index, index
while (left >= 0 and nums[left] == target) or (
right < len(nums) and nums[right] == target
):
if left >= 0 and nums[left] == target:
left -= 1
if right < len(nums) and nums[right] == target:
right += 1
return [left + 1, right - 1]

Comment