假設某無序數組A,首尾元素都是0,其他元素值都大於零,且不重複。每個數值都表明一個高度。ios
要求找出A[1] 到A[N-2]之間的任一高點(高點定義是:某點的值大於其先後元素值),要求時間複雜度爲O(Log(N)).數組
好比數組{0,8,9,4,5,1,3,6,7,0},其中高點爲9,5,7.spa
/\ /\code
/ \/\ / blog
/ \/ get
0894513670input
思路:要求爲時間複雜度爲O(Log(N)),那麼遍歷數組確定沒法實現,借鑑二分查找的思路,判斷每一個點的趨勢,某點上升趨勢的話,則後面必然有高點,前面不必定有;降低趨勢的話,相反。it
1 #include <iostream> 2 using namespace std; 3 enum trend 4 { 5 up = 0, 6 down, 7 submit, 8 peak, 9 foot, 10 none 11 }; 12 //get the thrend by checking the previous and following numbers. 13 trend getThrend(int a[], int count){ 14 if(count == 3) 15 { 16 if(a[0] > a[1]) 17 { 18 if(a[1] > a[2]) 19 return down; 20 else 21 return foot; 22 } 23 else 24 { 25 if(a[1] > a[2]) 26 return peak; 27 else 28 return up; 29 } 30 } 31 else 32 return none; 33 } 34 //find the peak point by using binary searching 35 void findOneHighPoint(int a[], int begin, int end){ 36 int mid = (begin+end)/2; 37 if(getThrend(&a[mid-1], 3) == peak) 38 { 39 cout<<"find one peak "<<a[mid]<<endl; 40 return; 41 } 42 if(getThrend(&a[mid-1], 3) == up) 43 findOneHighPoint(a, mid+1, end); 44 else 45 findOneHighPoint(a, begin, mid-1); 46 } 47 48 //input a array, begin end with 0 49 void main(){ 50 int a[10] = {0,8,9,4,5,6,6,6,7,0}; 51 findOneHighPoint(a, 1, 8); 52 }