题目描述:
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.
Your algorithm's runtime complexity must be in the order of O(log n).
Example 1:
Input: nums = [4,5,6,7,0,1,2], target = 0
Output: 4
Example 2:
Input: nums = [4,5,6,7,0,1,2], target = 3
Output: -1
算法描述:
- 首先通过二分法找到数组的pivot,在这个点之前数组升序,在这个点之后数组升序,且之前的序列都大于之后的
- 确定要查找的数据位于哪一个序列
- 在升序排列的子序列用二分法查找数据位置
算法实现:
class Solution {
public:
int search(vector<int>& nums, int target) {
if(nums.empty())return -1;
int i,j,k;
i = 0; j = nums.size() - 1;
while(i < j){
k = int((i + j)/2);
if(nums[i] <= nums[k] && nums[k] <= nums[j]){
k = nums.size();
break;
}
else if(j == i + 1){
k = j;
break;
}
else if(nums[i] > nums[k]) j = k;
else if(nums[j] < nums[k]) i = k;
}
if(target == nums[0])return 0;
else if(target < nums[0]) i = k, j = nums.size() - 1;
else i = 1, j = k - 1;
while(i <= j){
k = int((i + j)/2);
if(nums[k] == target)return k;
else if(nums[k] > target) j = k - 1;
else i = k + 1;
}
return -1;
}
};