Given a sorted array of integers, 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].
For example,
Given[5, 7, 7, 8, 8, 10]and target value 8,
return[3, 4].
解题思路:
(1)我们先来看看时间复杂度为O(n)的算法,分别从左遍历和从右遍历数组,找到目标数的第一个下标位置分为是要求解的目标值的起始和结束位置。Java代码实现如下:
public class Solution {
public int[] searchRange(int[] A, int target) {
int res[] = new int[2];
res[0] = -1;
res[1] = -1;
//向左找
for(int i = 0 ; i < A.length; i++){
if(A[i] == target){
res[0] = i;
break;
}
}
//向右找
for(int i = A.length - 1