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.
分析:二分法,首先将left和right进行比较,然后将left和mid相比较,确定递增序列,然后更改left或right的值。
public class Solution {
public int findMin(int[] nums) {
if(nums==null)
return 0;
int n=nums.length;
int left=0,right=n-1;
int mid;
while(left<right){
mid=left+(right-left)/2;
if(nums[left]<=nums[right])
return nums[left];
else if(nums[left]>nums[right]&&nums[mid]<nums[right]){
right=mid;
}else if(nums[left]>nums[right]&&nums[left]<=nums[mid]){
left=mid+1;
}
}
return nums[left];
}
}
154. Find Minimum in Rotated Sorted Array II
数组中可能存在重复的数字,此时有一种情况,无法判断左边和右边哪一边是递增的,即中间的等于左边的和右边的时候,此时只能将left+1,right-1.
public class Solution {
public int findMin(int[] nums) {
if(nums==null)
return 0;
int n=nums.length;
int left=0,right=n-1;
int mid;
while(left<right){
mid=left+(right-left)/2;
if(nums[left]<nums[right])
return nums[left];
else if(nums[left]==nums[right]&&nums[left]==nums[mid]){
left++;
right--;
}
else if(nums[left]>=nums[right]&&nums[mid]>=nums[left])
left=mid+1;
else if(nums[left]>=nums[right]&&nums[mid]<=nums[right])
right=mid;
}
return nums[left];
}
}