题目:Search in Rotated Sorted Array
Suppose a sorted array 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
).
You are given a target value to search. If found in the array return its index, otherwise return -1
You may assume no duplicate exists in the array.
思路:
(1)找到临界点
(2)对数组进行复位
(3)二分查找法
代码:
int search(int* nums, int numsSize, int target) {
int l=0;
int r=numsSize-1;
int* newArray=(int* )malloc(sizeof(int)*numsSize);
while(l < r)
{
int m=(l+r)/2;
if(nums[l] < nums[r]) //左和右比较
{
r = l;
}
else
{
if(nums[m] >= nums[l]) //加上等号
{
l=m+1;
}
else
{
r=m; //等于m
}
}
}
int mark=l;
//进行数组复位
for(int i=0;i<numsSize;i++)
{
newArray[i]=nums[(i+l)%numsSize];
}
//二分查找法
l=0;
r=numsSize-1;
while(l < r)
{
int m=(l+r)/2;
if(newArray[m] > target) r=m-1;
else if(newArray[m] < target) l=m+1;
else return (m+mark)%numsSize;
}
if(l==r && newArray[l]==target)
{
free(newArray);
return (l+mark)%numsSize;
}
free(newArray);
return -1;
}