Find Minimum in Rotated Sorted Array
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.
思路:
变形后的二分查找
我的代码:
public class Solution { public int findMin(int[] num) { if(num == null || num.length == 0) return -1; int left = 0; int right = num.length - 1; while(left + 1 < right) { int mid = (left + right)/2; int leftVal = num[left]; int rightVal = num[right]; int midVal = num[mid]; if(leftVal <= midVal && midVal < rightVal) return num[left]; else if(midVal > rightVal) left = mid; else right = mid; } if(num[left] <= num[right]) return num[left]; else return num[right]; } }
学习之处;
此种方法是改种后的二分查找,常规二分查找 left <= right left = mid - 1 or right = mid + 1,而此时变形为left = mid, right = mid,这样的话,如果判断条件还是left<=right,则无法跳出循环了,所以只能是left + 1 < right
posted on 2015-03-08 10:26 zhouzhou0615 阅读(133) 评论(0) 编辑 收藏 举报