题目153:
Suppose an array sorted in ascending order 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.
class Solution {
public int findMin(int[] nums) {
//给定升序的旧数组,但是新数组是由旋转生成的,你也不知道旋转方式,查找其中最小的。
//思路:无重复数,于是使用二分查找。由于新数组的特点是左边第大,右边小,如果mid大于high说明最小值在左边,反之在右边。
int low=0,high=nums.length-1;
while(low<high){
int mid=(low+high)/2;
if(nums[mid]>nums[high]){
//说明最小值在右边
low=mid+1;
}else{
//则在左边
high=mid;
}
}
return nums[high];
}
}
题目154:
Follow up for "Find Minimum in Rotated Sorted Array":
What if duplicates are allowed?Would this affect the run-time complexity? How and why?
Suppose an array sorted in ascending order 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.
The array may contain duplicates.
分析:
class Solution {
public int findMin(int[] nums) {
//原本排序好的数组,给定旋转数组(即将数组的前n个放置在数组的最后面),找出其中最小的数组
//思路:根据前面无重复采用二分查找,但是由于存在重复,例如:10111 中间值和两头值相等,无法确定中间的1是前面数组的还是后面数组的
//所以当碰到中间值相等的情况,只能依次查找
int low=0;
int high=nums.length-1;
int midIndex=low;//防止全部为一样的元素
while(nums[low]>=nums[high]){
//如果low和high相差一个,则high即为最小
if(high-low==1){
return nums[high];
}
//中间值
midIndex=(high+low)/2;
if(nums[midIndex]==nums[low]&&nums[midIndex]==nums[high]){
//中间值相等,只能顺序查找
return orderSearch(nums,low,high);
}
//正常情况
if(nums[midIndex]>=nums[low]){
//在后面
low=midIndex;
}else if(nums[midIndex]<=nums[high]){
high=midIndex;
}
}
return nums[midIndex];
}
//顺序查找最小值
public int orderSearch(int []nums,int start,int end){
int res=nums[start];
for(int i=start+1;i<=end;i++){
if(res>nums[i]){
res=nums[i];
}
}
return res;
}
}