题目
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.
分析
用二分法来实现
但是边界条件困扰了我很久。
什么时候用<= ,什么时候用<
实现
class Solution {
public:
int search(vector<int>& nums, int target) {
if (nums.size() == 0)
return -1;
int len = nums.size();
int left=0, right = len -1 , mid=0;
// <=
while (left <= right)
{
mid = (left + right) / 2;
if (target == nums[mid])
return mid;
// <=
if (nums[left] <= nums[mid])
{
if (nums[left] <= target&& target <= nums[mid])
right = mid - 1;
else
left = mid + 1;
}
else
{
if (nums[mid] <= target && target <= nums[right])
left = mid + 1;
else
right = mid - 1;
}
}
return -1;
}
};