题目
Number: 33
Difficulty: Hard
Tags: Array, Binary Search
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.
题解
一个有序数组被从中间某个位置反转过一次,变为两部分有序的数组,从中找出目标值。假设没有重复的值。
思路还是二分查找,但是需要仔细考虑每一种情况。
代码
int search(vector<int>& nums, int target) {
int l = 0, h = nums.size() - 1;
while(l < h){
int mid = l + (h - l) / 2;
if(nums[mid] == target)
return mid;
if(nums[l] <= nums[mid]){
if(nums[mid] > target && nums[l] <= target)
h = mid - 1;
else
l = mid + 1;
}
else{
if(nums[mid] < target && nums[h] >= target)
l = mid + 1;
else
h = mid - 1;
}
}
return nums[l] == target ? l : -1;;
}