Wednesday, October 9, 2013

Search in Rotated Sorted Array I [Leetcode]

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.

Solution: binary search; it would be more interesting if there are duplicates in the array [see follow up question].

class Solution {
public:
    int searchHelper(int A[], int begin, int end, int target){
        if(begin>end) return -1;
        int middle = (begin+end)/2;
        //Binary search
        if(A[middle]==target)
            return middle;
        if(A[middle]<A[end]){ //the right part is sorted in increasing order
            if(A[middle]>target || A[end]<target)
                return searchHelper(A, begin, middle-1, target);
            return searchHelper(A, middle+1, end, target);
        }
        //the left part is sorted in increasing order
        if(A[middle]<target || A[begin]>target)
            return searchHelper(A, middle+1, end, target);
        return searchHelper(A, begin, middle-1, target);
    }
    int search(int A[], int n, int target) {
        // Note: The Solution object is instantiated only once and is reused by each test case.
        if(n<=0) return -1;
        return searchHelper(A, 0, n-1, target);
    }
};

No comments:

Post a Comment