public int search(int[] nums, int target) {
if(nums.length ==0) return -1;
if(nums.length ==1){
if(nums[0] == target) return 0;
else return -1;
}
int low = 0;
int high = nums.length - 1;
int index = subIndex(nums,low,high);
if(index != -1){
int val = binarySearch(nums,low,index,target);
if (val != -1) return val;
return binarySearch(nums,index+1,high,target);
}
return binarySearch(nums,low,high,target);
}
public static int subIndex(int [] nums,int low,int high){
while (low <= high){
int mid = low + ((high - low )>> 1);
if(nums.length < 1) return -1;
if(nums[mid] > nums[mid+1]) return mid;
else if( nums[mid] < nums[low] ) high = mid ;
else if (nums[mid] > nums[high]) low = mid ;
else return -1;
}
return -1;
}
public static int binarySearch(int[] nums,int low,int high,int target){
while (low <= high){
int mid = low + ((high - low)>>1);
if(nums[mid] == target) return mid;
else if (nums[mid] < target) low = mid + 1;
else high = mid -1;
}
return -1;
}
展开