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.
(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.
问题分析:在旋转数组中查找给定元素是否存在。拿到这个题目想到的就是遍历O(n),当然这样很简单,但是看到题目难度是hard而且还是部分有序的数组,所有考虑是否有更加优化的办法,排序数组我们就联想到二分查找。这里旋转数组实际上就是把已经排序的数组前部分拿到后面,它满足下面的性质,后面部分数组递增且元素全小于前面部分的最小元素,前部分元素也是递增且都大于后半部分的任何一个元素。因此我们这里就涉及到二层的比较。先用middle比较,然后再看数据分布于前半部分还是后半部分。采用二分查找的方式。时间复杂度为O(logn),实现代码如下:
class Solution {
public:
int search(vector<int>& nums, int target) {
int size=nums.size();
if(size==0) return -1;
int low=0,high=size-1,middle=0;
while(low<=high){
middle=(low+high)/2;
if(nums[middle]==target) return middle;
if(nums[low]<=nums[middle]){
if(nums[low]<=target&&target<nums[middle]){
high=middle-1;
}
else
low=middle+1;
}
else{
if(nums[middle]<target&&target<=nums[high]){
low=middle+1;
}
else
high=middle-1;
}
}
return -1;
}
};