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) {
int length = nums.size();
int first = 0;
int last = length;
while(first != last)
{
const int mid = (first + last) / 2;
if(target == nums[mid])
return mid;
if(nums[first] <= nums[mid])
{
if(nums[first] <= target && target < nums[mid])
{
last = mid;
}
else
{
first = mid + 1;
}
}
else
{
if(target > nums[mid] && nums[last - 1] >= target)
{
first = mid + 1;
}
else
{
last = mid;
}
}
}
return -1;
}
};
1.二分的思想来做,所以不用去判断vector为空的情况,为空就是first==last的情况。
2.二分的使用场景大多数是对有序的,针对部分有序的情况,也可以使用二分法来查找元素。二分法的思想是对一个有序的数组,找出个中间元素,比中间元素大的就在右边,比中间元素小的就在左边。 二分的模式都是比较统一的,middle值跟target进行比较,一旦发现相等,就直接返回索引。当不同时,再分情况讨论。针对该题的情况,因为middle跟两边值的大小关系是不确定的,因此先要对middle和两边值的情况进行比对,然后再来判断值在哪儿边,由于是二分法,数值不在左边就在右边,所以找出肯定在一边的情况,那么其他的情况就是在另外一边。比如
1. 数组为4567123当target为6时,此时first和last都比中间元素小而且target也比中间元素小 需要判定元素在左边还是右边
2. 数组为4567123当target为2时,此时first和last都比中间元素小而且target也比中间元素小 需要判定元素在左边还是右边
3. 数组为6712345当target为3时,此时first和last都比中间元素大而且target也比中间元素大 需要判定元素在左边还是右边
4. 数组为6712345当target为3时,此时first和last都比中间元素大而且target也比中间元素大 需要判定元素在左边还是右边
该题的解题思路要对,否则会在分类的过程中将自己弄晕。