您的位置:首页 > 其它

Find Minimum in Rotated Sorted Array

2015-08-12 15:04 274 查看
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.

比较中间元素,比末尾大,在右侧查找,否则在左侧。

头比尾小,则没有旋转,最小的是头。

public int findMin(int[] num) {
if(num==null||num.length==0)
return 0;
return find(num,0,num.length-1);
}
private int find(int[] num,int low,int high){
if(low==high)
return num[low];
if(high-low==1)
return Math.min(num[low], num[high]);
int mid=(high+low)/2;
if(num[low]<num[high])//no rotated
return num[low];
if(num[mid]>num[high])//go right
return find(num,mid+1,high);
else					//go left
return find(num,low,mid);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: