public int search(int[] nums, int target) {
if (nums.length == 0) {
return -1;
}
if (nums.length == 1) {
return target == nums[0]?0:-1;
}
int i = 0;
int j = nums.length-1;
while (i<=j) {
//从中间把数组分为两部分,肯定有一半是有序的
//中间值是目标值直接返回
int mid = (i+j)/2;
if (nums[mid] == target) {
return mid;
}
//如果左半边是有序的
if (nums[0]<=nums[mid]) {
//如果目标值在范围内,直接在这个范围内用二分
if (nums[0]<=target&&target<nums[mid]) {
j = mid-1;
}else {
//在另一半继续判断,及时这一半是无序的,
// 但是经过上面一样的步骤就是分为两半,又会有一半是有序的
i = mid+1;
}
}else {
//以此类推
if (nums[mid]<target&&target<=nums[nums.length-1]) {
i = mid+1;
}else {
j = mid-1;
}
}
}
return -1;
}
05-01
363