Monday, December 29, 2014

Find Minimum in Rotated Sorted Array II (LeetCode Array)

Question:  Follow up for "Find Minimum in Rotated Sorted Array":
What if duplicates are allowed?
Would this affect the run-time complexity? How and why?
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.
The array may contain duplicates.

Idea: Consider the worst case as [2,1,2,2,2,2,2,....,2]. Binary search can not tell which half contains the minimum. Therefore just scan from left to right to get the minimum.

Time: O(n) Space: O(1)

Code: 
 public class Solution {  
   public int findMin(int[] num) {  
     int result=Integer.MAX_VALUE;  
     for(int i:num)  
       result=Math.min(result,i);  
     return result;  
   }  
 }  

1 comment: