问题
Given an array of integers 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].
For example,
Given [5, 7, 7, 8, 8, 10] and target value 8,
return [3, 4].
思路
简单的二分查找,由于有相同的元素,需要后面加了几个把附近的找出来。
ps:之前在公司项目也这样找过一次,不过要先排序再查找。
代码(越写越觉得不对劲,写的太冗余了,勉强ac)
class Solution {
public int[] searchRange(int[] nums, int target) {
//升序 找到起始的位置;原始的二分查找,再找旁边的几个。
int[] find = new int[2];
find[0]=-1;find[1]=-1;
if(nums.length==0)
return find;
int result =binarySearch(0,nums.length-1,nums,target);
if(result == -1)
return find;
else
return findNearBy(result,target,nums);
}
public int binarySearch(int start,int end,int[] nums,int target){
if(start>end){
return -1;
}
int mid = (start+end)/2;
if(nums[mid] == target){
return mid;
}
if(target>nums[mid]){ //右边
return binarySearch(mid+1,end,nums,target);
}else{
return binarySearch(start,mid-1,nums,target);
}
}
public int[] findNearBy(int index,int target,int[]nums){
int start = index; int end =index;
while(start>0){ //注意溢出 这里index=0没有算到,要后面判断一次
if(nums[start]==target){
start--;
}else{
break;
}
}
// if(start ==0){ //0的情况
if(nums[start]!=target){
start = start+1;
}
// }
while(end<nums.length-1){
if(nums[end]==target){
end ++;
}else break;
}
// if(end == nums.length-1){ //length-1
if(nums[end] != target){
end = end-1;
}
// }
int[] temp = new int[2];
temp[0] = start;
temp[1] = end;
return temp;
}
}