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:
1 | Input: nums = [5,7,7,8,8,10], target = 8 |
Example 2:
1 | Input: nums = [5,7,7,8,8,10], target = 6 |
解法
看到O(logn)的时间复杂度,就要想到每次应该把处理的范围减半,这样一来,只有二分和树形结构能达到此目的,对于这个题目,当然是二分啦。可以先用二分查找查找到target,然后以target为中心向左右查找最早和最晚出现的节点。
具体代码如下:
1 | class Solution { |
当然,严格而言,以上算法的时间复杂度的最坏情况O(n),因为当所有元素均相同且为target需要遍历整个数组,这个时候为了达到严格的时间复杂度要求,可以以找到最小和找到最大的对应坐标为终止条件,更改终止条件代码,最小的index的特征有index = 0或nums[index-1]!=target,最大的条件同理。同时,若不满足该终止条件而又是target的话,若为寻找最小index,下一次搜索应该变化end,寻找最大index,下一次搜索应向右变化start,具体代码如下:
1 | class Solution { |