Leetcode 153: Find Minimum in Rotated Sorted Array, leetcoderotated
Find Minimum in Rotated Sorted ArrayTotal Accepted:
21207Total Submissions:
65855
Suppose a sorted array is rotated at some unknown to you beforehand.
(I. e .,0 1 2 4 5 6 7
Might become4 5 6 7 0 1 2
).
Find the minimum element.
You may assume no duplicate exists in the array.
[Analysis]
If num [mid] and adjacent elements are not ordered, the minimum value can be obtained. Otherwise, check whether low and high are ordered and jump to the half of the unordered one.
[Note]
NONE
[CODE]
public class Solution { public int findMin(int[] num) { if(num==null || num.length < 1) return 0; // ask interviewer which value should return: Integer.MIN_VALUE or throw a Exception. int low = 0, high = num.length-1; while(low < high) { int mid = low + (high-low)/2; int x = num[mid]; if( mid != num.length-1 && x>num[mid+1]){ return num[mid+1]; } else if(num[mid] < num[low]) { high = mid; } else if(num[mid] > num[high]) { low = mid; } else { return num[low]; } } return num[low]; }}