import java.util.ArrayList;publicclassSolution{publicintminNumberInRotateArray(int[] array){int len = array.length;if(len ==0){return0;}else{int min = array[0];for(int i =0; i < len; i++){if(array[i]< min){
min = array[i];}}return min;}}}
对上述方法稍微优化一下
import java.util.ArrayList;publicclassSolution{publicintminNumberInRotateArray(int[] array){int len = array.length;if(len ==0)return0;for(int i =0; i < len -1; i++){if(array[i]> array[i +1])return array[i +1];}return array[0];}}
import java.util.ArrayList;publicclassSolution{publicintminNumberInRotateArray(int[] array){int len = array.length;if(len ==0){return0;}else{int left =0;int right = len -1;while(left < right){int mid = left +(right - left)/2;//如果array[mid]>array[right],则最小值一定在右半边if(array[mid]> array[right]){
left = mid +1;}//解决特殊情况,如:[2,1,2,2,2],只能逐个比较elseif(array[mid]== array[right]){
right = right -1;}//array[mid]<array[right],最小值一定是array[mid]或在左半边else{
right = mid;}}return array[left];}}}
改进的二分法
import java.util.ArrayList;publicclassSolution{publicintminNumberInRotateArray(int[] array){int len = array.length;if(len ==0){return0;}else{int left =0;int right = len -1;while(left < right){int mid = left +(right - left)/2;//如果array[mid]>array[right],则最小值一定在右半边if(array[mid]> array[right]){//如果array[mid]>array[mid+1],则最小值为array[mid+1]if(array[mid]>array[mid +1]){return array[mid +1];}//否则在右半边else{
left = mid +1;}}//解决特殊情况,如:[2,1,2,2,2],只能逐个比较elseif(array[mid]== array[right]){
right = right -1;}//array[mid]<array[right],最小值一定是array[mid]或在左半边else{//如果array[mid-1]>array[mid],则最小值为array[mid]if(array[mid -1]>array[mid]){return array[mid];}//否则在左半边else{
right = mid;}}}return array[left];}}}