思路: binary search。 和33题差不多。其实就是简单的binary search加上一些condition。注意,这边其实两种情况,mid左边sorted和mid右边sorted。大致就是分这两种情况考虑。下面给出两个代码。一个是我自己写的,还有一个是高赞解答,但是被我自己修改过:
// 自己写的
class Solution {
public int findMin(int[] nums) {
int left = 0, right = nums.length - 1;
while(left <= right){
int mid = left + (right - left) / 2;
if(mid < nums.length - 1 && nums[mid] > nums[mid + 1]){// break case 1
return nums[mid + 1];
}else if(mid > 0 && nums[mid - 1] > nums[mid]){// break case 2
return nums[mid];
}else if(nums[mid] >= nums[left] && nums[mid] >nums[nums.length -1]){ // the second condition ensures the arry is not the last special case
left = mid + 1;
}else if(nums[mid]< nums[left] ){
right = mid ;
}else{ // special case, array is not rotated
return nums[0];
}
}
return 100;
}
}
// 高赞修改
class Solution {
public int findMin(int[] nums) {
int left = 0, right = nums.length - 1;
while(left < right){
int mid = left + (right - left) / 2;
if(nums[left] < nums[right]) return nums[left]; // special case , the array is not rotated
if(nums[mid] < nums[left]){ // right sorted, pivot is in the left
right = mid;
}else{ // left sorted, pivot is in the right
left = mid + 1;
}
}
return nums[left]; // Loop exits when hi == lo == the smallest value in the array
}
}
总结:
- binary search