问题描述:
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.
个人解题的大致步骤:1.由反转数组得到正常的有序数组。
2.利用二分法查找target。
3.找出正常有序数组中的元素下标与反转后的数组的下标的关系。
AC代码如下:
</pre><pre name="code" class="cpp">int search(vector<int>& nums, int target)
{
int len = nums.size();
int pos;//用于存放原有序数组翻转的位置
for (pos = 0;pos < len - 1;pos++)
{
if (nums[pos] > nums[pos + 1])
break;
}
//ori_nums正常有序数组
vector<int>ori_nums;
for (int i = pos + 1;i < len;i++)
ori_nums.push_back(nums[i]);
for (int i = 0;i <= pos;i++)
ori_nums.push_back(nums[i]);
//二分查找target
int low = 0;
int high = len - 1;
int mid;
int ori_pos = -1;
while (low <= high)
{
mid = low + (high - low) / 2;
if (ori_nums[mid] > target)
high = mid - 1;
else if (ori_nums[mid] < target)
low = mid + 1;
else
{
//找到后记得跳出循环
ori_pos = mid;
break;
}
}
//证明没找到
if (ori_pos == -1)
return -1;
else
{
//当前正常有序数组的index转换到反转数组中的index
//分 反转点pos前后两种情况
if (target >= nums[0])
return (ori_pos - len + pos + 1);
else
return (ori_pos + pos + 1);
}
}
还有一个 LeeTCode 81. Search in Rotated Sorted Array II 就是数组中有重复的元素,基本和这一题一样,其实还更简单一点,这里就不再列出代码了。