和153题不同的是这题中可能会有重复数字,在二分查找过程中,如果遇到一样的数字,直接忽略,进行下一次start+1/stop-1查找即可,具体解决代码如下:
public class Solution {
public int findMin(int[] nums) {
int result = 0;
if (nums.length == 0) {
return 0;
} else if (nums.length == 1) {
return nums[0];
} else if (nums.length == 2) {
return Math.min(nums[0], nums[1]);
} else {
return find(nums, 0, nums.length - 1);
}
}
public int find(int[] nums, int start, int stop) {
if (nums[start] < nums[stop]) {
return nums[start];
}
if (stop - start == 1) {
return Math.min(nums[start], nums[stop]);
} else {
int middle = (start + stop) / 2;
if (nums[middle] > nums[start]) {
return find(nums, middle, stop);
} else if (nums[middle] == nums[start]) {
return find(nums, start + 1, stop);
} else {
return find(nums, start, middle);
}
}
}
}