leetcode [33] Search in Rotated Sorted Array

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
 
题目大意:
在一个旋转数组中寻找给定值,并返回下标,如果旋转数组中不存在给定值,则返回-1。
 
解法:
看到算法的时间约束,采用二分查找进行实现,因为数组是旋转数组,所以数组一定是先递增后递减,可能没有递减的部分。所以采用二分进行查找的时候,可能分到的数组,是一直递增的,也可能是先增后减的,也可能是一直减小的,如果是一直增大的,那么就用数组开始值,结束值和目标值进行比较,如果不在范围,那么这个区域的继续二分并没有意义。
 
自己实现的C++:
class Solution {
private:
    int searchCore(vector<int>nums,int begin,int end,int target){
        if(begin>end||begin<0||end>=nums.size()) return -1;
        if(nums[begin]==nums[end] && nums[begin]==target) return begin;
        if(nums[begin]<=nums[end]&&(nums[begin]>target||nums[end]<target)) return -1;        
        int mid=(end-begin)/2+begin;
        int l=searchCore(nums,begin,mid,target);
        int r=searchCore(nums,mid+1,end,target);
        if(l!=-1) return l;
        else return r;
    }

public:
    int search(vector<int>& nums, int target) {
        int res=-1;
        res=searchCore(nums,0,nums.size()-1,target);
        return res;
    }
};

 

posted @ 2019-03-24 19:42  小白兔云  阅读(139)  评论(0编辑  收藏  举报