把一個數組最開始的若干個元素搬到數組的末尾,我們稱之爲數組的旋轉。
題目:輸入一個遞增排序的數組的一個旋轉,輸出旋轉數組的最小元素。
例如數組{3,4,5,1,2}爲{1,2,3,4,5}的一個旋轉,該數組的最小值爲1。
Java版本:
public class findMin {
//順序查找
public static int MinInOrder(int[] arr,int start,int end) {
int result = arr[start];
for(int i = start + 1;i<=end;i++){
if(arr[i]<result)
result = arr[i];
}
return result;
}
public static int findmin(int[] arr){
try {
if(arr == null || arr.length <= 0)
System.out.println("Invalid parameters");
} catch (Exception e) {
e.printStackTrace();
}
int start = 0;
int end = arr.length - 1;
int mid = start;
if(arr[end]>arr[start] || end==start )
return arr[start];
while((end-start)>1){
mid = start + (end - start)/2;
//若起點、終點、中間點的值都相等時,無法通過移動兩個指針來縮小範圍,只能採用順序查找的方法
if(arr[mid]==arr[start] && arr[start]<=arr[end])
return MinInOrder(arr,start,end);
if(arr[mid]>=arr[start])
start = mid;
else if(arr[mid]<=arr[end])
end = mid;
}
return arr[end];
}
public static void main(String[] args) {
//arr數組是一個遞增數組旋轉之後的旋轉數組
// 1、典型輸入,單調升序的數組的一個旋轉
int arr1[] = { 4, 5, 2, 3 };
// 2、有重複數字,並且重複的數字剛好的最小的數字
int arr2[] = { 3, 4, 5, 1, 1, 2 };
// 3、有重複數字,但重複的數字不是第一個數字和最後一個數字
int arr3[] = { 3, 4, 5, 1, 2, 2};
// 4、有重複的數字,並且重複的數字剛好是第一個數字和最後一個數字
int arr4[] = { 1, 0, 1, 1, 1};
// 5、單調升序數組,旋轉0個元素,也就是單調升序數組本身
int arr5[] = { 4, 5, 6, 7, 8, 9 };
// 6、數組中只有一個數字
int arr6[] = { 8 };
// 7、輸入NULL
int arr7[] = null;
System.out.println("arr1數組最小值爲:"+findmin(arr1));
System.out.println("arr2數組最小值爲:"+findmin(arr2));
System.out.println("arr3數組最小值爲:"+findmin(arr3));
System.out.println("arr4數組最小值爲:"+findmin(arr4));
System.out.println("arr5數組最小值爲:"+findmin(arr5));
System.out.println("arr6數組最小值爲:"+findmin(arr6));
System.out.println("arr7數組最小值爲:"+findmin(arr7));
}
}