Wednesday, April 29, 2015

[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:
start            1          pivot              2           end
Let's do a binary search. If mid > target, there is only one case where we need to move the start pointer, i.e. target falls in interval 2, and mid falls in interval 1. For other cases, we need to move the end pointer.
If mid < target, there is only one case where we need to move the end pointer, i.e. target falls in interval 1 and mid falls in interval 2. For other cases, we need to move the start pointer.

class Solution {
public:
    int search(vector<int>& nums, int target) {
        int start = 0 ;
        int end = nums.size() - 1;
        while(start <= end)
        {
            int mid = start + (end-start)/2;
            if(nums[mid] == target) return mid;
            
            if(nums[mid] > target)
            {
                if(target <= nums[end] 
                    && nums[mid] > nums[end])
                {
                    start = mid + 1;
                }
                else
                {
                    end = mid - 1;
                }
            }
            else
            {
                if(target > nums[end] 
                    && nums[mid] < nums[end])
                {
                    end = mid - 1;
                }
                else
                {
                    start = mid + 1; 
                }
            }
        }
        return -1;
    }
};