Wednesday, September 17, 2014

[Leetcode] 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.
Analysis:
After rotated, half of the array, either [b, m] or [m, e] must be sorted. If the target was in the range, do the binary search for the half, otherwise, do the binary search for another half. 

class Solution {
public:
    int search(int A[], int n, int target) {
        int b = 0;
        int e = n-1;
        while(b <= e)
        {
            int m = (b+e)/2;
            if (A[m] == target)
                return m;
            else if (A[m] < A[e])
            {
                if (target > A[m] && target <= A[e])
                    b = m + 1;
                else
                    e = m - 1;
            }
            else
            {
                if (target < A[m] && target >= A[b])
                    e = m - 1;
                else
                    b = m + 1;                
            }
        }
        
        return -1;
    }
};

No comments:

Post a Comment