find minimum in rotated sorted array

递归解法

思路:递归加二分。

如果中间元素的值大于左边的元素,那么最小值在右边。(说明该数组经过rotate,大的数跑到前面了)

如果中间元素的值小于左边的元素,那么最小值在左边。(后面的元素肯定比这个中间元素大)

注意边界的处理,上面说的两种情况只适合经过rotate的数组,所以需要先判断该数组是否经过rotate

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
public static int findMin(int[] nums){
if (nums == null || nums.length == 0){
return 0;
}
if (nums.length == 1){
return nums[0];
}
return findMin(nums, 0, nums.length - 1);
}

public static int findMin(int[] nums, int left, int right){
if (nums[left] < nums[right]){
return nums[left];
}
if (left == right){
return nums[left];
}
if (left + 1 == right){
return Math.min(nums[left], nums[right]);
}

int mid = (left + right) / 2;

//solution1和solution2任选一个
//solution1
if (nums[mid] > nums[left]){
return findMin(nums, mid+1, right);
}else{
return findMin(nums, left, mid);
}

//solution2
//return Math.min(findMin(nums, left, mid), findMin(nums, mid+1, right));
}

二分解法

思路:

和递归的解法相同,同样也需要注意边界的处理。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
public static int findMin(int[] nums){
if (nums == null || nums.length == 0){
return 0;
}
int l = 0, r = nums.length - 1;

while (l <= r){
if (nums[l] <= nums[r]){
return nums[l];
}

int m = (i + j) / 2;
if (nums[m] >= nums[i]){
l = m + 1;
}else{
r = m;
}
}
return nums[l];
}