1.Simple Easy Thinking Solution
Binary Search
- Time Complexity: O(logn)
class Solution {
public int findMin(int[] nums) {
// The difference between 33. Search in Rotated Sorted Array and this one is:
// This question find the mim and the other is to find the target.
int start = 0, end = nums.length -1;
while(start +1 <end){
int mid = start + (end - start)/2;
if(nums[mid] > nums[start]){
if(nums[mid] < nums[end] && nums[mid-1] < nums[mid]) end = mid;
else start = mid;
}
else if(nums[mid] < nums[start]){
if(nums[mid] > nums[end] && nums[mid-1] > nums[mid]) start = mid;
else end = mid;
}
}
if(nums[start] > nums[end]) return nums[end];
return nums[start];
}
}
2.Improved Binary Search Solution2
- Time Complexity: O(logn)
Analysis: In the rotated array,like x+3,x+4,x+5,x(min),x+1,x+2;
In ths array, we have the conclusion that if start < end, the array is in rotate.
- start > end if this array is rotated, so we can find mim value in this scope;
if start <end, it means that the start is the min. - how to verify the first asmuption:
I use the array[x+3,x+4,x(min),x+1,x+2]:
we can see that, the smaller will always in the right, the numbers in the left will always more than the right numbers.
class Solution {
public int findMin(int[] nums) {
/*Thinking:
1. end < start ==> rotated ;
2. array: x+2,x+3,x(min),x+1;
*/
int start = 0, end = nums.length -1;
while(start + 1 < end){
int mid = start + (end - start)/2;
if(nums[mid] < nums[end]){
end = mid;
}
else{
start = mid;
}
}
if(nums[end] < nums[start]) return nums[end];
return nums[start];
}
}
3. Divide and Conquer分治法
- Time Complexity: O(logn)
Recursive
Thoughts: Every time, separate the array into two parts, find the min in the two parts, compare the two min and find the minmize number.
class Solution {
public int findMin(int[] nums) {
return Fmin(nums, 0, nums.length-1);
}
private int Fmin(int[] nums, int start, int end){
if(start == end || start +1 == end) return Math.min(nums[start],nums[end]);
if(nums[start] < nums[end]) return nums[start];
int mid = start + (end - start)/2;
return Math.min(Fmin(nums, mid, end), Fmin(nums, start, mid));
}
}
本文对比了三种寻找旋转数组中最小元素的方法:简单易懂的二分查找、优化过的二分搜索和分治法。通过实例解析,展示了如何利用这些算法在O(logn)的时间复杂度下找到最小值。

被折叠的 条评论
为什么被折叠?



