如题,要求找到target所在位置的最大和最小值
题中nums为顺序增序,要求查找时间为o(logn),那么考虑用二分法,先随机找到一个,然后左右扩增
代码如下
public class searchRange {
public static int[] searchRange(int[] nums, int target) {
int a = search(nums,0, nums.length-1, target);
int[] r = new int[2];
r[0]=a;
r[1]=a;
if(a==-1)return r;
int i=a;
while(nums[i]==target){
r[0]=i;
i--;
if(i<0)break;
}
i=a;
while(nums[i]==target){
r[1]=i;
i++;
if(i>=nums.length)break;
}
return r;
}
public static int search(int[] nums, int left, int right, int target){
if(left>right)return -1;
int middle = (left+right)/2;
if(nums[middle]>target){
return search(nums, left,middle-1,target);
}else if(nums[middle]<target){
return search(nums, middle+1,right,target);
}else {
return middle;
}
}
public static void main(String[] args) {
int[] a = {1};
int[] r = searchRange(a,1);
System.out.println(r[0]);
System.out.println(r[1]);
}
}
网友评论