33. 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.
解析
// 33. Search in Rotated Sorted Array
class Solution_33 {
public:
// 本质:不管什么情况,都是只是low,high进行移动,二分查找时候一定记住要有常数步的前进,防止进入死循环
//input : [3, 1]
// 1
//Output : -1 bug1:加等号
// Expected : 1
int search(vector<int>& nums, int target) {
if (nums.size()==1&&nums[0]==target)
{
return 0;
}
int low = 0, high = nums.size()-1;
while (low<=high)
{
int mid = low + (high - low) / 2;
if (nums[mid]==target)
{
return mid;
}
if (nums[mid]>target)
{
if (nums[low]<=nums[mid]) //低半部分有序; bug 1有序部分要用等号
{
if (nums[low]<=target) //target在低半部分序列中
{
high = mid - 1;
}
else
{
low = mid + 1;
}
}
else // 后半部分有序,且nums[mid]>target;必位于前半部分
{
high = mid - 1;
}
}
else
{
if (nums[mid]<=nums[high]) //后半部分有序
{
if (nums[high]>=target)
{
low = mid + 1;
}
else
{
high = mid - 1;
}
}
else //nums[mid]>target 且前部分有序
{
low = mid + 1;
}
}
}
return -1;
}
int search2(int A[], int n, int target) {
int low = 0, high = n - 1;
while (low<=high)
{
int mid = low + (high - low) >> 1;
if (A[mid]==target)
{
return mid;
}
if (A[mid]>=A[low]) //低半部分有序;先比较区间,在比较关键字target
{
if (A[mid]>target&& target>=A[low]) //bug 2: 调整那个,就不用等号
{
high = mid - 1;
}
else
{
low = mid + 1;
}
}
else //后半部分有序
{
if (A[mid]<target&&target<=A[high])
{
low = mid + 1;
}
else
{
high = mid - 1;
}
}
}
return -1;
}
int search_ref(vector<int>& nums, int target) {
int l = 0, r = nums.size() - 1;
while (l <= r) {
int mid = (l + r) / 2;
if (target == nums[mid])
return mid;
// there exists rotation; the middle element is in the left part of the array
if (nums[mid] > nums[r]) {
if (target < nums[mid] && target >= nums[l])
r = mid - 1;
else
l = mid + 1;
}
// there exists rotation; the middle element is in the right part of the array
else if (nums[mid] < nums[l]) {
if (target > nums[mid] && target <= nums[r])
l = mid + 1;
else
r = mid - 1;
}
// there is no rotation; just like normal binary search
else {
if (target < nums[mid])
r = mid - 1;
else
l = mid + 1;
}
}
return -1;
}
};
题目来源