Monday, December 29, 2014

Find Minimum in Rotated Sorted Array (LeetCode Array)

Question:  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).
Find the minimum element.
You may assume no duplicate exists in the array.

Idea: Binary Search. If the array is rotated, the minimum should be in the abnormal half, where abnormal means the head is larger than the tail (larger  than or equals when the half has only 1 element). The algorithm can be implemented either recursively or iteratively.

Time: O(lgn) Space: O(1)

Recursive Code:
 public class Solution {  
   public int findMin(int[] num) {  
     return binarySearch(num,0,num.length-1);  
   }  
   public int binarySearch(int[] num, int left,int right)  
   {  
     if(num[left]<=num[right])  
       return num[left];  
     else if(left+1==right)  
       return Math.min(num[left],num[right]);  
     else  
     {  
       int mid=(left+right)/2;  
       if(num[left]>=num[mid])  
         return binarySearch(num,left,mid);  
       else  
         return binarySearch(num,mid+1,right);  
     }  
   }  
 }  


Iterative Code: 
 public class Solution {  
   public int findMin(int[] num) {  
     int left=0;  
     int right=num.length-1;  
     while(left<=right)  
     {  
       if(num[left]<=num[right])  
         return num[left];  
       if(left+1==right)  
         return Math.min(num[left],num[right]);  
       int middle=(left+right)/2;  
       if(num[left]>=num[middle])  
         right=middle;  
       else  
         left=middle+1;  
     }  
     return -1;  
   }  
 }  

No comments:

Post a Comment