思路:半排序数组,进行判断,一共四种情况:
- 数组前半部分有序且目标值在前半数组中
- 数组后半部分有序且目标值在后半数组中
- 数组前半部分有序且目标值在后半数组中
- 数组后半部分有序且目标值在前半数组中
前两种直接进行二分查找,后两种进行递归。
public int search(int[] nums, int target) {
int start = 0;
int end = nums.length-1;
int mid = (start+end)/2;
while (start<=end){
mid = (start+end)/2;
if(start == end){
if(nums[start]==target)
return start;
else
return -1;
}
if(nums[start]<=nums[mid] && (target<=nums[mid] && target>=nums[start])){//数组前半部分有序且目标值在前半数组中
return binarySearch(nums,target,start,mid);
}
else if(nums[start]>=nums[mid] && (target>=nums[mid] && target<=nums[end])){//数组后半部分有序且目标值在后半数组中
return binarySearch(nums,target,mid,end);
}
else if(nums[start]<=nums[mid] && (target>nums[mid] || target<nums[start])){//数组前半部分有序且目标值在后半数组中
start = Math.min(mid + 1, end);
}
else if((nums[start]>=nums[mid] && (target<nums[mid]) || target>nums[end])){//数组后半部分有序且目标值在前半数组中
end = Math.max(mid - 1, start);
}
}
return -1;
}
private int binarySearch(int[] nums,int target,int low, int high){
while (low<=high){
int mid = (high+low)/2;
if(nums[mid]>target)
high = mid-1;
else if(nums[mid]<target)
low = mid+1;
else
return mid;
}
return -1;
}