Shortest answer for now (Java code)


  • 0
    I
    public int findMin(int[] num) {
        int l = 0, r = num.length - 1;
    
        while (r - l > 1) {
            int mid = l + (r - l) / 2;
    
            if (num[mid] > num[l] && num[mid] > num[r]) {
                l = mid;
            } else {
                r = mid;
            }
        }
    
        return Math.min(num[l], num[r]);
    }
    

    The point is, the middle element must be wither smaller than both the start and end or bigger than both of them if it is rotated.
    Or, if it is not rotated, just do the basic binary search.


  • 0
    K

    this one is also short and easy to read (Java)

        public int findMin(int[] num){
        	int m = num[0];
            for(int n:num){
                while (m<n){
                	m=n;
                }
                if(m>n){
                	return n;
                }
            }
            return num[0];
        }
    

    Python version:

        def findMin(self, num):
            m = num[0]
            for n in num[1:]:
                while m<n:
                    m=n
                if m>n:
                    return n
            return num[0]

  • 0
    B

    Your solution is the same as mine. But I think his is better cause it's O(logn) while yours is O(n).


Log in to reply
 

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