Find Minimum in Rotated Sorted Array

Suppose a sorted array 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.

二分法

说明

因为要找最小的元素那么我们每次拿mid跟最右边的比较大小, 如果大于最右边的则说明mid在左边的逆序里, 那么把左边界设为mid. 如果小于最右边则说明mid在最小值和右边界之间, 把右边界设为mid

复杂度

时间O(logn)空间 O(1)

代码

public int findMin(int[] nums) {
    if (nums == null || nums.length == 0) {
        return -1;
    }
    int left = 0, right = nums.length - 1;
    while (left + 1 < right) {
        int mid = left + (right - left) / 2;
        if (nums[mid] > nums[right]) {
            left = mid;
        } else {
            right = mid;
        }
    }
    return Math.min(nums[left], nums[right]);
}

Find Minimum in Rotated Sorted Array II

二分法

说明

由于此题输入可能有重复元素,因此在num[mid] == num[right]时无法使用二分的方法缩小start或者end的取值范围因为左边的值可能跟右边相同。此时只能使用递增start/递减end逐步缩小范围。

复杂度

时间 worst: O(n) 空间 O(1)

代码

public int findMin(int[] nums) {
    if (nums == null || nums.length == 0) {
        return -1;
    }
    int left = 0, right = nums.length - 1;
    while (left + 1 < right) {
        int mid = left + (right - left) / 2;
        if (nums[mid] > nums[right]) {
            left = mid;
        } else if (nums[mid] < nums[right]){
            right = mid;
        } else {
            right--;
        }
    }
    return Math.min(nums[left], nums[right]);
}

lpy1990
26 声望10 粉丝