题目:
34. Find First and Last Position of Element in Sorted Array
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: List[int], target: int) -> List[int]:
if not nums: return [-1, -1]
n = len(nums)
l, r = 0, n-1
index = -1
while l <= r:
mid = (l+r) // 2
if nums[mid] == target:
index = mid
break
elif nums[mid] > target:
r = mid - 1
else:
l = mid + 1
if index == -1:
return [-1, -1]
i, j = index, index
while i-1 >= 0 and nums[i-1] == target:
i -= 1
while j+1 < n and nums[j+1] == target:
j += 1
return [i, j]
字典代码:
class Solution:
def searchRange(self, nums: List[int], target: int) -> List[int]:
if not nums:
return [-1,-1]
num_dict = dict()
for i in range(len(nums)):
num_dict.setdefault(nums[i], [])
num_dict[nums[i]].append(i)
if num_dict.get(target, None):
return [num_dict[target][0], num_dict[target][-1]]
else:
return [-1,-1]
循环代码:
class Solution:
def searchRange(self, nums: List[int], target: int) -> List[int]:
i = 0
j = len(nums)-1
res = []
if not nums or nums[i] > target or nums[j] < target:
return [-1,-1]while(i<len(nums)):
if nums[i] == target:
res.append(i)
break
else:
i += 1
while(j>=0):
if nums[j] == target:
res.append(j)
break
else:
j -= 1
if res:
return res
else:
return [-1,-1]