Search in Rotated Sorted Array
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]
).
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.
Your algorithm's runtime complexity must be in the order of O(log n).
Example 1:
Input: nums = [4,5,6,7,0,1,2]
, target = 0
Output: 4
Example 2:
Input: nums = [4,5,6,7,0,1,2]
, target = 3
Output: -1
class Solution {
public:
int search(vector<int>& nums, int target) {
int l=0,h=nums.size(),mid;
int n=h;
if(nums.size()==0)return -1;
else if(nums.size()==1)
{
if(nums[0]==target)return 0;
else
return -1;
}
else if(h==2)
{
if(target==nums[0])
return 0;
else if(target==nums[1])
return 1;
else
return -1;
}
int m=-1,first=nums[0],last=nums[n-1];
--h;
while(l<=h)
{
mid=(l+h)/2;
if((mid-1)>=0&&nums[mid-1]>nums[mid])
{
m=mid;
break;
}
else if(mid+1<n&&nums[mid]>nums[mid+1])
{
m=mid+1;
break;
}else if(nums[mid]<first&&nums[mid]<last)
{
h=mid-1;
}else{
l=mid+1;
}
}
if(m==-1)
{
l=0,h=n-1;
}else
if(target>=nums[m]&&target<=last)
{
l=m,h=n;
}else if(target>=first&&target<=nums[m-1])
{
l=0,h=m-1;
}
else{
return -1;
}
while(l<=h)
{
mid=(l+h)/2;
if(target==nums[mid])
return mid;
else if(target<nums[mid])
{
h=mid-1;
}else if(target>nums[mid]){
l=mid+1;
}
}
return -1;
}
};