34. Find First and Last Position of Element in Sorted Array
Description
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]
我的代码
class Solution:
def searchRange(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
l = 0
r = len(nums) - 1
m = int((l + r) / 2)
r1 = -1
r2 = -1
while (l <= r):
if nums[m] == target and (m == 0 or nums[m - 1] < target):
r1 = m
r2 = m
l += 1
break
else:
if nums[m] >= target:
r = m - 1
else:
l = m + 1
m = int((l + r) / 2)
r = len(nums) - 1
while (l <= r):
if nums[m] == target and (m == r or nums[m + 1] > target):
r2 = m
break
else:
if nums[m] <= target:
l = m + 1
else:
r = m - 1
m = int((l + r) / 2)
return [r1,r2]
思路:
一开始准备第一个和最后一个一起找,发现不行。因为找第一个和最后一个判断遇到等于target的元素判断方法不一样。
- 时间复杂度: O(log(n))
- 出错: 各种条件考虑不清楚