Wednesday, January 7, 2015

LeetCode 33: Search in Rotated Sorted Array

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.
public class Solution {
    public int search(int[] A, int target) {
        // Adopt modified binary search
        int n = A.length;
        int lo = 0, hi = n-1;
        
        return rank(A, lo, hi, target);
    }
    
    private int rank(int[] A, int lo, int hi, int target)
    {
        if (hi < lo)
            return -1;        
        
        int mid = (lo+hi)/2;
            
        if (A[mid] == target)
            return mid;
            
        if (A[mid] > A[lo])
        {
            if (target>=A[lo] && target<A[mid])
                return rank(A, lo, mid-1, target);
            else
                return rank(A, mid+1, hi, target);
        }
        else if (A[mid] < A[lo])
        {
            if (target>A[mid] && target<=A[hi])
                return rank(A, mid+1, hi, target);
            else
                return rank(A, lo, mid-1, target);
        }
        else
        {
            if (A[mid] != A[hi])
                return rank(A, mid+1, hi, target);
            else
            {
                int result = rank(A, lo, mid-1, target);
                
                if (result != -1)
                    return result;
                else
                    return rank(A, mid+1, hi, target);
            }
        }
    }
}

No comments:

Post a Comment