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.
Subscribe to see which companies asked this question
class Solution {
public:
int search(vector<int>& nums, int target) {
if (nums.size() == 0)
return -1;
int left = 0;
int right = nums.size()-1;
while (left <= right)
{
int mid = (left+right)/2;
if (nums[mid] == target)
return mid;
//因为这里是left right下标里面的数的比较,有可能left == right
// 譬如 [1],0 这种情况, left == right == 0, 所以 nums[left] == nums[right]
// 所以这里要用 '<='
// in one word, mid can be == left
if (nums[left] <= nums[mid])
{
// 这里的>=很好理解,因为 target 肯定不疼雨 nums[mid]
// 但是 target >= nums[left] 都应该继续往同一边搜索
if (target < nums[mid] && target >= nums[left])
{
right = mid-1;
}
else
{
left = mid+1;
}
}
else
{
if (target <= nums[right] && target > nums[mid])
{
left = mid+1;
}
else
{
right = mid-1;
}
}
}
return -1;
}
};