Search in Rotated Sorted Array问题及解法

来源:互联网 发布:万能数据恢复大师 编辑:程序博客网 时间:2024/05/29 13:09

问题描述:

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.

问题分析:

寻找数组中一个元素是否存在,实际上就是一种查找算法。用线性查找法肯定能找到,但是时间复杂度为O(N)。因而我们采取一种二元查找法,先找出最大的元素索引,然后依次再利用二元查找法寻找target值得索引。


过程详见代码:

class Solution {public:    int search(vector<int>& nums, int target) {    if(nums.empty()) return -1;        int low = 0;        int high = nums.size() - 1;        int maxi = findMaxIndex(nums);        if(nums[maxi] == target) return maxi;        else if(nums[maxi] < target) return -1;        else{        if(nums[low] > target) return findTarget(nums,target,maxi+1,high);        else return findTarget(nums,target,low,maxi);}    }        int findMaxIndex(vector<int>& nums)    {    int low = 0;        int high = nums.size() - 1;        int maxi = high;         if(nums[low] < nums[high]) return high;      while(low < high)    {        int mid = low + (high - low) / 2;        if(nums[mid] > nums[mid + 1]) return mid;        else if(nums[mid] >= nums[low])        {        low = mid + 1;}else{high = mid - 1;}}return low;}int findTarget(vector<int>& nums, int target,int low, int high){        while(low < high)        {        int mid = low + (high - low) / 2;        if(nums[mid] == target) return mid;        else if(nums[mid] < target) low = mid + 1;        else high = mid;}return nums[high] == target ? low : -1;}};


原创粉丝点击