思路:二分。
若一个数组被旋转,二分之后必有一段是有序的,并且最小的数一定在无序的那段。
最小数的前一个数必定比它大。
代码:
class Solution {
public int findMin(int[] nums) {
if (nums.length == 1) {
return nums[0];
}
int left = 0;
int right = nums.length - 1;
if (nums[left] < nums[right]) {
return nums[left];
}
while (left <= right) {
int mid = (left + right) / 2;
if (nums[mid] > nums[mid + 1]) {
return nums[mid + 1];
}
if (nums[mid] < nums[mid - 1]) {
return nums[mid];
}
// 左侧有序
if (nums[left] <= nums[mid]) {
left = mid + 1;
}
else {
right = mid - 1;
}
}
return -1;
}
}
class Solution {
public int findMin(int[] nums) {
int res = Integer.MAX_VALUE;
int left = 0;
int right = nums.length - 1;
while (left <= right) {
int mid = (left + right) / 2;
// 左侧有序
if (nums[left] <= nums[mid]) {
res = Math.min(res, nums[left]);
left = mid + 1;
continue;
}
// 右侧有序
if (nums[mid] <= nums[right]) {
res = Math.min(res, nums[mid]);
right = mid - 1;
continue;
}
}
return res;
}
}