假设一个排好序的数组在其某一未知点发生了旋转(比如 0 1 2 4 5 6 7 可能变成 4 5 6 7 0 1 2 )。你需要找到其中最小的元素。
在线评测地址:https://www.lintcode.com/problem/find-minimum-in-rotated-sorted-array/?utm_source=sc-v2ex-fks
样例 1:
输入:[4, 5, 6, 7, 0, 1, 2]
输出:0
解释:
数组中的最小值为 0
样例 2:
输入:[2,1]
输出:1
解释:
数组中的最小值为 1

public class Solution {
    /**
     * @param nums: a rotated sorted array
     * @return: the minimum number in the array
     */
    public int findMin(int[] nums) {
        int left = 0, right = nums.length - 1;
        // 二分法
        while (left < right){
            // 最小值在 left
            if (nums[left] < nums[right]){
                return nums[left];
            }
            int mid = left + (right - left) / 2;
            // 最小值在[left, mid]
            if (nums[left] > nums[mid]){
                right = mid;
            }
            // 最小值在(mid, right]
            else{
                left = mid + 1;
            }
        }
        return nums[left];
    }
}
更多题解参考:https://www.jiuzhang.com/solution/find-minimum-in-rotated-sorted-array/?utm_source=sc-v2ex-fks
     1 
                    
                    cczeng      2020-09-08 09:35:40 +08:00 
                    
                    👍 
                 | 
            
     2 
                    
                    sakura1      2020-09-30 11:51:34 +08:00 
                    
                    这个题我也做过,有重复元素的情况就另说了 
                 | 
            
     3 
                    
                    hakunamatata11   OP @sakura1 嗯嗯 
                 |