LeetCode

来源:互联网 发布:现代设计方法优化设计 编辑:程序博客网 时间:2024/04/30 01:18

Find Minimum in Rotated Sorted Array

 

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.  


该题仍然局部有序,仍然使用二分查找,只是判断移动游标的方式不一样,另外针对{6,5,4,3,2,1}这种case ,需要特殊处理

public static int findMin(int[] num) {int start =  0 , end = num.length - 1;int result = 0;int key = (num[start] - num[end]);while(true){int mid = (start+end)/2;if((num[start] - num[mid]) * key > 0){//mid处于后半段end = mid;}else if((num[start] - num[mid]) * key < 0){//mid处于前半段start = mid;}else {//start ,end 都已经移动到最小值的位置if(key < 0){result = num[start];}else{result = num[end];}break;}}//对于 有序递减 的Case,该算法将游标移动到了最大值处,此时末尾即是最小值。return  (result < num[num.length - 1]) ? result:num[num.length - 1];}



Submission Result: Accepted


0 0
原创粉丝点击