Accepted Java solution with binary search O(log N)


  • 0
    W
    public class Solution {
        public int findMin(int[] num) {
            
            if(num.length == 0) return 0;
            if(num.length == 1) return num[0];
            
            int l=0,r=num.length - 1, mid;
            
            while(true){
                mid=(r+l)/2; // binary-search
                if(mid == l)break; // range reduced to only 2 elements
                
                if(num[mid]>num[r]){ l = mid;}
                else if(num[mid]<num[l]){ r = mid;}
                else {return num[l];}
            }
            
            return num[l]<num[r] ? num[l] : num[r];
        }
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.