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 ; i >= 0; i--){
if(A[i] == target){
res[1] = i;
break;
}
}
return res;
}
}
(2)若要求时间复杂度为O(log n),我们可以利用二分查找的方法,该算法的时间复杂度为O(log n)。通过两次二分法查找,找到目标值的左边界和右边界,需要对二分查找法稍微加以修改。当查找右边界时,即当A[middle]小于等于目标数target时,low游标自增1继续往右走。同理当查找左边界时,即当A[middle]大于等于目标数target时,high游标自减1继续往左走。以题中所给例子为例,查找的过程图如下。
①查找右边界过程图:
②查找左边界过程图:
Java代码实现:
public class Solution {
public int[] searchRange(int[] A, int target) {
int len = A.length;
int res[] = new int[2];
res[0] = -1;
res[1] = -1;
int low1 = 0, high1 = len - 1;
//查找右边界
while(low1 <= high1){
int middle1 = (low1 + high1) / 2;
if(A[middle1] <= target)
low1 = middle1 + 1;
else
high1 = middle1 - 1;
}
int low2 = 0, high2 = len - 1;
//查找左边界
while(low2 <= high2){
int middle2 = (low2 + high2) / 2;
if(A[middle2] >= target)
high2 = middle2 - 1;
else
low2 = middle2 + 1;
}
if(low2 <= high1){
res[0] = low2;
res[1] = high1;
}
return res;
}
}