Find Minimum in Rotated Sorted Array

Suppose an array sorted in ascending order 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.

Example 1:

Input: [3,4,5,1,2] 
Output: 1

Example 2:

Input: [4,5,6,7,0,1,2]
Output: 0

这道题只有两种情况,1是先升,然后drop,再升,2是一直上升,利用nums[nums.length - 1] 和nums[mid]的关系,来判断mid落在哪一阶段,如果nums[mid] <= target,说明 要么是落在第二阶段,要么整个都是上升的。 这种情况下,只要end = mid, 就能缩小范围,另外注意这道题是要返回的数组数值,不是index

class Solution {
    public int findMin(int[] nums) {
        if(nums.length == 0 || nums == null){
            return -1;
        }
        
        
        int start = 0, end = nums.length-1;
        
        //if nums[mid] > nums[start], in first uprise 
        // int target = nums[nums.length -1];
        while(start + 1 < end){
            int mid = start + (end - start) /2 ;
            
            if(nums[mid] <= nums[end]){
                end = mid;
            }else{
                start = mid;
            }
           
        }
        
        if(nums[start] <= nums[end]){
            return nums[start];
        }else{
            return nums[end];
        }
    }
}

Last updated