算法题之无序数组找到任一高点

假设某无序数组A,首尾元素都是0,其余元素值都大于零,且不重复。每一个数值都代表一个高度。

要求找出A[1] 到A[N-2]之间的任一高点(高点定义是:某点的值大于其前后元素值),要求时间复杂度为O(Log(N)).

比如数组{0,8,9,4,5,1,3,6,7,0},其中高点为9,5,7.

      /\     /\

               /   \/\    /   

             /          \/    

             0894513670

思路:要求为时间复杂度为O(Log(N)),那么遍历数组肯定无法实现,借鉴二分查找的思路,判断每个点的趋势,某点上升趋势的话,则后面必然有高点,前面不一定有;下降趋势的话,相反。

 

 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 }

 

 

 

posted @ 2014-07-24 10:48  Sparkles  阅读(164)  评论(0编辑  收藏  举报