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
假设以升序排序的数组在事先未知的某个轴上旋转。(即[0,1,2,4,5,6,7]可能会变成[4,5,6,7,0,1,2])。
将为您提供要搜索的目标值。 如果在数组中找到,则返回其索引,否则返回-1。
您可以假定数组中不存在重复项。
算法的运行时复杂度必须为O(log n).的量级。
看上去题目挺简单,但是O(log n).已经规定死了我们使用的方法为二分法。想到二分法不难,难的是对数据的处理,我是浪费了很多时间才通过的。看来我二分法玩的还不是很熟。
class Solution {
public:
int search(vector<int>& nums, int target) {
int size = nums.size();
if(!size)
return -1;
int pos = 0, left = 0, right = size - 1;
for(pos = size/2; left < right;){
if(nums[pos] == target)
return pos;
if (nums[right] == target)
return right;
if (nums[left] == target)
return left;
if ((nums[pos] > nums[left] && (target < nums[left] || target > nums[pos])) ||
(nums[pos] < nums[right] && target < nums[right] && target > nums[pos])) {
left = pos + 1;
pos = (--right + left) / 2;
}
else{
right = pos - 1;
pos = (right + ++left) / 2;
}
}
return pos < size && nums[pos] == target?pos:-1;
}
};