和153題不同的是這題中可能會有重復數(shù)字奄侠,在二分查找過程中,如果遇到一樣的數(shù)字埋涧,直接忽略板辽,進行下一次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);
}
}
}
}