Java Solution(Binary Search)


  • 0
    G
    1. First check if it is rotated or not by comparing nums[start] and nums[end]. If not, return the first value.
    2. Use binary search, I like use while(start+1 < end) as the condition for BS , then check the final nums[start] nums[end], it's convenient:
    public class Solution {
        public int findMin(int[] nums) {
            int start = 0;
            int end = nums.length - 1;
            if (nums[start] < nums[end]) return nums[start];
            while (start + 1 < end) {
                int mid = start + (end - start)/2;
                if (nums[mid] > nums[mid+1]) return nums[mid+1];
                else if (nums[mid] > nums[start]) start = mid;
                else end = mid;
            }       
            if (nums[start] < nums[end]) return nums[start];
            else return nums[end];
            
        }
    }
    

Log in to reply
 

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