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.
Example
Given [4, 5, 6, 7, 0, 1, 2] return 0
解决这个问题首先必须知道二分法。二分法是针对有序数组,从中间找到某一个值。
public int binarySearch(int[] nums, int target) {
if (nums == null || nums.length == 0) {
return -1;
}
int start = 0, end = nums.length - 1;
while (start <= end) { //target区间是[start,end] 这是循环不变量
//int mid = (start+end)/ 2;
int mid=start+(end-start)/2;//解决整形溢出问题
if (nums[mid] == target) {
return mid;
} else if (nums[mid] < target) {
//or start = mid;
start = mid + 1;//target区间在[mid+1,end]
} else {
// or end = mid;//target区间在[start,mid-1]
end = mid - 1;
}
}
return -1;
}
public int binarySearch(int[] arr, int target,int low ,int high) {
if (low<=high) {
int mid=(low+high)/2;
if (arr[mid]==target) {
return mid;
}
if (arr[mid]>target) {
return binarySearch(arr, target, low, mid-1);
}
if (arr[mid]<target) {
return binarySearch(arr, target,mid+1, high);
}
}
return -1;
}
经典代码需要牢记于心。
旋转数组也是用于这种方法
public int findMin(int[] nums) {
int left=0;
int right=nums.length-1;
if (nums[right]>nums[left]) {
return nums[left];
}
while(left+1<right){
int middle=(left+right)/2;
if (nums[middle]>=nums[left]) {
left=middle;
}
if (nums[middle]<=nums[right]) {
right=middle;
}
}
return nums[right];
}