
题目:
Suppose an array sorted in ascending order 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.
思路:
1.题目中指出sorted array,find target使用二分法。
2.分为以下三种情况
(1)数组只有一个元素:nums[0]即为最小值。
(2)数组不是rotated sorted array,退化为sorted array:nums[0]即为最小值。
(3)数组是rotated sorted array:nums[start] > nums[end]:
a:nums[mid]大于nums[start].
b:nums[mid]小于nums[start].
代码:
public class Solution {
public int findMin(int[] nums) {
int start = 0,end = nums.length-1,mid = 0;
//length equals 1;
if(nums.length == 1){
return nums[0];
}
//is rotated sorted array;
while(nums[start] > nums[end] && start + 1 < end){
mid = start + (end - start)/2;
if(nums[mid] > nums[start]){
start = mid;
}else if(nums[mid] < nums[start]){
end = mid;
}
}
//is not rotated sorted array;
if(nums[start] < nums[end]){
return nums[start];
}
return nums[end];
}
}