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 X to search. If X found in the array return its index, otherwise return -1
Discussion
Case 1 : No duplicate exists in the array

public int search(int[] nums, int x) {
    int left = 0;
    int right= nums.length-1;
    while(left<=right){
        int mid = left + (right-left)/2;
        if(x == nums[mid])return mid;
        if(nums[left]<=nums[mid]){
            if(nums[left]<=x && x<nums[mid]){
                right=mid-1;
            }else{
                left=mid+1;
            }
        }else{
            if(nums[mid]<x && x<=nums[right]){
                left=mid+1;
            }else{
                right=mid-1;
            }
        }    
    }
    return -1;
}



Case 2 : Duplicate exists in the array


public int search(int[] nums, int x) {
    int left = 0;
    int right= nums.length-1;
    while(left<=right){
        int mid = left + (right-left)/2;
        if(x == nums[mid])return mid;
        if(nums[left]<nums[mid]){
            if(nums[left]<=x && x<nums[mid]){
                right=mid-1;
            }else{
                left=mid+1;
            }
        }else if(nums[left]>nums[mid]){
            if(nums[mid]<x && x<=nums[right]){
                left=mid+1;
            }else{
                right=mid-1;
            }
        }else{
            left++;
        }    
    }
    return -1;
}

Comments

Popular posts from this blog

Longest Subarray with Sum greater than Equal to K

Consistent Hashing