您的位置:首页 > 其它

寻找旋转排序数组中的最小值 II

2017-07-07 15:22 337 查看
假设一个旋转排序的数组其起始位置是未知的(比如0 1 2 4 5 6 7 可能变成是4 5 6 7 0 1 2)。

你需要找到其中最小的元素。

数组中可能存在重复的元素。

给出[4,4,5,6,7,0,1,2]  返回
0

解题思路:

还是采用二分的思想,每次取中间mid,如果A[mid]>A[end],说明最小值在mid和end之间。

如果A[mid]<A[end],说明最小值在mid和start之间。

如果A[mid]==A[end],无法判断最小值在左边还是右边,end的位置肯定是大于等于最小值的,因此就end--;

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
if(num==null||num.length==0){
return -1;
}
int start=0;
int end=num.length-1;
int mid;
while(start+1<end){
mid=start+(end-start)/2;
if(num[mid]>num[end]){
start=mid;
}else if(num[mid]<num[end]){
end=mid;
}else{
end--;
}
}
if(num[start]>=num[end]){
return num[end];
}else{
return num[start];
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: