题目:
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]
.
代码如下:
package leetcode;
//由于时间复杂度是log n,所以只能用二分查找的方法;关键是怎么调用二分查找呢?
//思路:1、先在数组中找到目标数字(二分查找),找不到就返回-1;
public class SearchForARange {
static int func(int[] nums, int start, int end, int target){
while (start<=end){
int mid = (start+end)/2;
if (nums[mid]==target){
return mid;
}else if(target<nums[mid]){
end = mid-1; //本题目的关键:理解二分查找的精髓——通过mid来查找target
//递归的精髓:把问题化成子问题!!!每次都只在半分枝查找
//判断的永远是那个[mid] ==target !!
// 而不是用[mid+1] or [mid-1]去判断!失去了二分法的意义
}else
start = mid+1;
}
return -1; //就是判断递推判断:在这半分枝,是否存在[mid] ==target,
//如果不存在。就返回-1,存在就返回这个mid!
}
public static int[] searchRange(int[] nums, int target){
int[] result = new int[]{-1, -1}; //提前初始化为-1,-1;
int pos = func(nums, 0, nums.length-1, target);
if (pos==-1)
return result;
int temp = pos, first=pos, second=pos; //找到了这个点的位置;
//二分法,每次找到mid后,会分两半来查找,而本题直接分两半,
//前半分枝,每次只向前半分枝查找,直到找到第一个
while (temp != -1){
first = temp;
temp = func(nums, 0, temp-1, target);
}
temp = pos;
//后面的半分枝,每次只在后半边查找,直到找到最后一个;
while (temp != -1){
second = temp;
temp = func(nums, temp+1, nums.length-1, target);
}
result[0] = first;
result[1] = second;
return result;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] a = {1,2,2,3,3,3};
for(int i:searchRange(a,2)) {
System.out.println(i);
}
}
}