Suppose a sorted array is rotated at some pivot unknown to you beforehand.
(i.e.,0 1 2 4 5 6 7might become4 5 6 7 0 1 2).
Find the minimum element.
Notice
You may assume no duplicate exists in the array.
Have you met this question in a real interview?
Yes
Example
Given[4, 5, 6, 7, 0, 1, 2]return0
Answer: https://leetcode.com/problems/find-minimum-in-rotated-sorted-array/description/
Tips: for rotate sorted array -- find the first position which is the number less than the last number in array
如果条件设定这个数组里可能有重复的数,则不能用二分法只能暴力循环比对!
https://leetcode.com/problems/search-in-rotated-sorted-array/description/
public class Solution {
public int FindMin(int[] nums) {
if (nums == null || nums.Length == 0){
return -1;
}
int start = 0, end = nums.Length -1;
int lastNumber = nums[end];
while (start +1 < end){
int mid = start + (end -start)/2;
if (nums[mid]< lastNumber){
end = mid;
}else{
start = mid;
}
}
if (nums[start] < nums[end]){
return nums[start];
}
return nums[end];
}
}
}