Search in Rotated Sorted Array
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.
Array、Binary Search
难
题目意思是一个旋转后的排序数组,让你查找一个value值,如果value存在则返回index,否则返回-1。解题思路是利用二分法去解决,分开两段,如有有一段不是排好序的,那说明另一段肯定是排好序的。主要有下面三种情况:
1)4567012:left<mid 、mid>right
2)0124567:left<mid、mid<right
3)7012456:left>mid、mid<right
由上可知,当left<mid的时候,左半部分肯定是排好序的,右半部分要么是排好序的,要么是没有排好序的。
int search(int* nums, int numsSize, int target)
{
int l = 0;
int r = numsSize-1;
while(l<=r)
{
int mid = l + (r-l)/2;
if(target == nums[mid])
return mid;
if(nums[l]<=nums[mid])//it is sorted in [l,mid], "=" contains an edge case:3, 1
{
if(nums[mid] > target && nums[l] <= target)
r = mid-1;
else
l = mid+1;
}
else//[mid,r] must be sorted, if [l,mid] not sorted
{
if(nums[mid] < target && nums[r] >= target)
l = mid+1;
else
r = mid-1;
}
}
return -1;
}