Leetcode中的Find Minimum in Rotated Sorted Array
看了题目基本就知道是什么题啦,然而我们还是放上原题。
https://leetcode.com/problems/find-minimum-in-rotated-sorted-array/
原题
Suppose a sorted array is rotated at some pivot unknown to you beforehand.
(i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2).
Find the minimum element.
You may assume no duplicate exists in the array.
翻译:在一个Rotated Sorted Array中寻找最小的元素(Rotate操作的步数并不知道),数组中没有重复的元素。
问题分析
二分查找看图说话,
如果是mid落到A点,那么往右边找,如果落到B点那么往左边找。
落到B点很好区分,只要mid
public int findMin(int[] nums)
{
int low = 0, high = nums.length - 1;
while(high - low > 1)
{
int mid = (high + low)/2;
if(nums[mid] >= nums[low])
{
if(nums[high] < nums[low])
{
low = mid + 1;
}
else
{
high = mid - 1;
}
}
else
{
high = mid;
}
}
return Math.min(nums[low],nums[high]);
}
同样的,我们接下来看看有重复元素的情况。