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.
(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.
Subscribe to see which companies asked this question
寻找最小值时关键在于 寻找,两个递增数组,第一个最大右边界,第二个最小左边界
class Solution {
public:
int bs(vector<int>& nums, int st, int en, int target)
{
if(st > en)
return -1;
int m;
while(st <= en)
{
m = st + (en - st)/2;
if(nums[m] == target)
{
return m;
}
if(nums[m] < target)
{
st = m + 1;
}else
{
en = m - 1;
}
}
return -1;
}
int search(vector<int>& nums, int target)
{
int l = 0;
int r = nums.size() - 1;
int m;
int pos = -1;
if(nums[l] < nums[r])
{
pos = 0;
return bs(nums, 0, r, target);
}
while(l < r)
{
if(r - l == 1)
{
pos = l;
break;
}
m = l + (r - l)/2;
if(nums[m] > nums[l])
{
l = m;
}else if(nums < nums[r])
{
r = m;
}
}
int lpos = bs(nums, 0, pos - 1, target);
int rpos = bs(nums, pos, nums.size() - 1, target);
if(lpos >= 0) return lpos;
if(rpos >= 0) return rpos;
return -1;
}
};