Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.
(i.e., 0 1 2 4 5 6 7
might become 4 5 6 7 0 1 2
).
Write a function to determine if a given target is in the array.
The array may contain duplicates.
解题思路:
一般对有序数组、表、集合等搜索某个目标时,使用二分法。
该题也不例外,我的思路是:先找出翻转的边界,比如题目中的例子,先找出7,0的位置,然后左右两段各自二分查找。
AC解:
public class Solution {
public boolean search(int[] nums, int target) {
int i;
int nlen = nums.length;
if(nlen==1)
{
if(nums[0]==target)
return true;
else
return false;
}
boolean flag = false; // not rotated
for(i=1;i<nlen;i++)
{
if(nums[i]>=nums[i-1])
continue;
else
{
flag = true; // rotated
break;
}
}
if(flag==false)
return find(nums,target,0,nlen-1);
else
return find(nums,target,0,i-1) || find(nums,target,i,nlen-1);
}
public boolean find(int[] nums,int target,int i,int j)
{
if(i<=j)
{
int l=i,r=j;
int mid = l+(r-l)/2;
if(nums[mid]==target)
return true;
else if(nums[mid]>target)
return find(nums,target,l,mid-1);
else
return find(nums,target,mid+1,r);
}
else
return false;
}
}