Leetcode:Search in Rotated Sorted Array

来源:互联网 发布:金融网络销售违法吗 编辑:程序博客网 时间:2024/06/01 10:33

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. 

You may assume no duplicate exists in the array.

思路:先遍历一遍数组,找出分割点,将数组分成low1~high1,low2~high2两个有序子数组,其中A[high2]<A[low1]。

如果A[low1]<=target,则在low1~high1区间二分查找;

如果A[low1]>target,则在low2~high2区间二分查找。

时间复杂度为O(logn + n)。

代码如下:

class Solution {public:    int binSearch(int A[],int begin,int end,int target)    {        while(begin <= end)        {            int mid = begin + (end - begin) >> 1;            if(A[mid] > target)                end = mid - 1;            else                if(A[mid] < target)                    begin = mid + 1;                    else                        return mid;        }        return -1;    }    int search(int A[], int n, int target) {        if(n == 0)return -1;        int i = 0;        while(i < n - 1 && A[i] < A[i + 1])            i++;        if(i == n - 1)        return binSearch(A,0,n - 1,target);        if(i < n - 1)        {            int low1 = 0;            int high1 = i;            int low2 = i + 1;            int high2 = n - 1;            if(A[low1] <= target)            {                int idx = binSearch(A,low1,high1,target);                if(idx >= 0)return idx;                else return -1;            }            else            {                int idx = binSearch(A,low2,high2,target);                if(idx >= 0)return idx;                else return -1;            }        }    }};


0 0
原创粉丝点击