Friday, April 15, 2016

[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 {
    
    private int searchAux(int[] nums, int target, int l, int r){
        if(1 == r - l){
            // more more more
            if(nums[l] == target){
                return l;
            }else{
                return -1;
            }
        }else if(1 > r - l){
            return -1;
        }else{
            int m = (l + r) / 2;
            // 0, 4 --> 2 
            if(nums[m] == target){
                return m;
            }else if(nums[m] > target){
                // abnormal range
                if(nums[l] > nums[m]){
                    return searchAux(nums, target, l, m);
                }else if(nums[r-1] < nums[m]){
                    if(target >= nums[l])
                        return searchAux(nums, target, l, m);
                    else
                        return searchAux(nums, target, m, r);
                    
                }else{
                    return searchAux(nums, target, l, m);
                }
                
            }else{
                if(nums[l] > nums[m]){
                    
                    if(target >= nums[l])
                        return searchAux(nums, target, l, m);
                    else
                        return searchAux(nums, target, m, r);
                    
                }else if(nums[r-1] < nums[m]){
                        return searchAux(nums, target, m, r);
                    
                }else{
                    return searchAux(nums, target, m, r);
                }
                
            }
        }
    }
    
    public int search(int[] nums, int target) {
        int len = nums.length;
        
        if(0 == len)
            return -1;
            
        return searchAux(nums, target, 0, len);
    }
}

No comments:

Post a Comment