假设一个旋转排序的数组其起始位置是未知的(比如0 1 2 4 5 6 7 可能变成是4 5 6 7 0 1 2)。
你需要找到其中最小的元素。
你可以假设数组中不存在重复的元素。
public class Solution {
/**
* @param num: a rotated sorted array
* @return: the minimum number in the array
*/
public int findMin(int[] num) {
// write your code here
int low=0;
int high=num.length-1;
while(low+1<high){
int mid=low+(high-low)/2;
if(num[mid]>num[high]){
low=mid;
}else if(num[mid]<num[high]){
high=mid;
}
}
if(num[high]<num[high-1]){
return num[high];
}
return num[0];
}
}
如果数组中可能存在重复的元素。那么上面的方法就不能使用。因为假设序列为1,1,1,0,1。搜索的时候查找到mid为1和low和high比较并不能得到最小值min是在前半部分还是后半部分。因此不能使用二分的方法了,只能使用顺序查找。代码如下:
public class Solution {
/**
* @param num: a rotated sorted array
* @return: the minimum number in the array
*/
public int findMin(int[] num) {
// write your code here
int min=num[0];
for(int i=1;i<num.length;i++){
if(num[i]<min){
min=num[i];
}
}
return min;
}
}