这道题目看了题目解答才做出来
旋转元素各不相同数组二分查找
自己代码:
public int search(int[] nums, int target)
{
if(nums.length==0)return -1;
if(nums.length==1&&nums[0]==target)return 0;
if(nums.length==1&&nums[0]!=target)return -1;
int low=0;
int high=nums.length-1;
int mid;
while(true)
{
mid=low+((high-low)>>2);
if(nums[mid]==target)return mid;
else
{
if(nums[mid]>nums[low])
{
if(target>=nums[low]&&target<nums[mid])
{
high=mid-1;
break;
}
else low=mid+1;
}
else
{
if(target>nums[mid]&&target<=nums[high])
{
low=mid+1;
break;
}
else high=mid-1;
}
}
}
if(low>high)return -1;
return Arrays.binarySearch(nums,low,high+1,target);
}
题目解答代码:
class Solution {
public int search(int[] nums, int target) {
int len = nums.length;
int left = 0, right = len-1;
while(left <= right){
int mid = (left + right) / 2;
if(nums[mid] == target)
return mid;
else if(nums[mid] < nums[right]){
if(nums[mid] < target && target <= nums[right])
left = mid+1;
else
right = mid-1;
}
else{
if(nums[left] <= target && target < nums[mid])
right = mid-1;
else
left = mid+1;
}
}
return -1;
}
}
反思:
- 为什么要用True循环呢?查找mid的过程本来就是和二分查找是类似的,所以直接low<=high就可以了。
- 不要想太多,不要把过程拆解来看,寻找有序的left和right,找完了之后还是要在这里面找target的呀!
网友评论