二刷有自己的思路,就是代码繁琐了
class Solution {
//二分查找的中间值
//如果比右边大,说明在翻转部分。
//此时若nums[mid]比target大,在左边找还是右边找?
//target比最左边小的话就去右边找。比最左边大去左边找
//此时若nums[mid]比target小,在左边找还是右边找?
//target在右边找
//如果比右边小,说明在正常部分
//此时若nums[mid]比target大,在左边找还是右边找?
//左边找
//此时若nums[mid]比target小,在左边找还是右边找?
//target比最右边大就去左边找。比最右边小就去右边找
public int search(int[] nums, int target) {
int lo=0;
int hi=nums.length-1;
int mid=0;
while(lo<=hi){
mid=lo+(hi-lo)/2;
if(nums[mid]>nums[hi]){
if(nums[mid]>target)
if(target<nums[lo])
lo=mid+1;
else if(target>nums[lo])
hi=mid-1;
else
return lo;
else if(nums[mid]<target)
lo=mid+1;
else
return mid;
}
else if(nums[mid]<nums[hi]){
if(nums[mid]>target)
hi=mid-1;
else if(nums[mid]<target){
if(nums[hi]<target)
hi=mid-1;
else if(nums[hi]>target)
lo=mid+1;
else
return hi;
}
else
return mid;
}
else
return (nums[hi]==target)?hi:-1;
}
return -1;
}
}
原文:https://www.cnblogs.com/wsshub/p/14864179.html