·二分法搜尋方法:
#include
using
namespace std;
intmin
(int
* numbers,
int length)
int index1 =0;
int index2 = length -1;
int indexmid = index1;
while
(numbers[index1]
>= numbers[index2]
) indexmid =
(index1 + index2)/2
;if(numbers[indexmid]
>= numbers[index1]
)else
if(numbers[indexmid]
<= numbers[index2])}
return numbers[indexmid];}
intmain()
;int value =
min(a,5)
; cout << value << endl;
system
("pause");
return0;
}
缺陷:當p1,middle,p2的值都相等時,演算法只會無腦傾向於右面,如果最小值在左面那就錯了。所以這種情況只能...(忘了)
·二分法和順序法相結合,避免二分法的缺陷:
演算法結束標誌:index1與index2相鄰時,演算法結束。index2就是答案。
具體實現如下:
#include
using
namespace std;
intmininorder
(int
*numbers,
int index1,
int index2)
}return result;
}int
min(
int* numbers,
int length)
int index1 =0;
int index2 = length -1;
int indexmid = index1;
while
(numbers[index1]
>= numbers[index2]
) indexmid =
(index1 + index2)/2
;if(numbers[index1]
== numbers[index2]
&& numbers[index2]
== numbers[indexmid])if
(numbers[indexmid]
>= numbers[index1]
)else
if(numbers[indexmid]
<= numbers[index2])}
return numbers[indexmid];}
intmain()
;int value =
min(a,1)
; cout << value << endl;
system
("pause");
return0;
}
11 旋轉陣列的最小數字
把乙個陣列最開始的若干個元素搬到陣列的末尾,我們稱之為陣列的旋轉。輸入乙個非遞減排序的陣列的乙個旋轉,輸出旋轉陣列的最小元素。例如陣列為的乙個旋轉,該陣列的最小值為1。我的 二分法 class min defsolution self,nums a nums 0 b nums 1 iflen num...
11 旋轉陣列的最小數字
把乙個陣列最開始的若干個元素搬到陣列的末尾,我們稱之為陣列的旋轉。輸入乙個遞增排序的陣列的乙個旋轉,輸出旋轉陣列的最小元素。例如,陣列 3,4,5,1,2 為 1,2,3,4,5 的乙個旋轉,該陣列的最小值為1。輸入 3,4,5,1,2 輸出 1 輸入 2,2,2,0,1 輸出 0 此題很容易想到順...
11 旋轉陣列的最小數字
class solution1 int res array 0 遍歷陣列,找出最小值 for int i 1 i array.length i return res class solution2 if nums.length 1 nums nums.length 1 nums 0 int p1 0...