[leetcode_33] Search in Rotated Sorted Array

Given a sorted array that has been rotated. For example: 0 1 2 3 4 5 6 7 8 9 after rotation becomes: 7 8 9 0 1 2 3 4 5 6
Given a target, return its index if it exists in the array, otherwise return -1.
Obviously, anyone can think of an O(n) approach.
Can we do better? O(log n)? Binary search? Just modify binary search a bit:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
class Solution {
public:
    int ans;
    void searchStep(int A[],int target,int left,int right) 
    {
        if(left > right)
            return;
        int mid = (left+right)/2;
        if(A[mid] == target)
        {
            ans = mid;
            return;
        }
        else
        {
            if(A[mid] > target)
            {
                if(A[right] > A[left])
                {
                    searchStep(A,target,left,mid-1);
                }
                else
                {
                    searchStep(A,target,left,mid-1);
                    searchStep(A,target,mid+1,right);
                }
            }
            else
            {
                if(A[right] > A[left])
                {
                    searchStep(A,target,mid+1,right);
                }
                else
                {
                    searchStep(A,target,mid+1,right);
                    searchStep(A,target,left,mid-1);
                }
            }
        }
    }
    int search(int A[], int n, int target) 
    {
        int left = 0;
        int right = n-1;
        ans = -1;
        searchStep(A,target,left,right);
        return ans;
    }
};
Licensed under CC BY-NC-SA 4.0