九章演算法--尋找數組波峰

來源:互聯網
上載者:User

標籤:style   blog   color   os   io   ar   2014   div   log   

題目描述:一 個數組A[1..n],假設數組中沒有任何相鄰兩數相等,滿足A[1]<A[2],A[n-1]>A[n]。A[i]被稱為波峰,若且唯若 A[i]>A[i-1]並且A[i]>A[i+1]。請找到數組中的一個波峰。假設數組中存在相鄰相等的數,該怎麼做?

二分法尋找一個波峰,

如果數組存在相鄰相等的元素則必須O(n)

 1 /************************************************************************* 2     > File Name: ArrayWaveCrest.cpp 3     > Author: zhoukang1991 4     > Mail: [email protected]  5     > Created Time: 2014年08月29日 星期五 21時36分24秒 6  ************************************************************************/ 7  8 #include <iostream> 9 #include <vector>10 #include <climits>11 using namespace std;12 13 int findcrest(const vector<int> &arr){14     int left = 0;15     int right = arr.size()-1;16     int n = arr.size();17     while(left <= right){18         int mid = left + (right-left)>>1;19         if(mid == 0){20             left = 1;21             continue;22         }23         if(mid == n-1){24             right = n-2;25             continue;26         }27 28         if( arr[mid] > arr[mid-1] && arr[mid] > arr[mid+1]){29             return arr[mid];30         }31         else if(arr[mid] < arr[mid-1]){32             right = mid-1;33         }34         else{35             left = mid+1;36         }37     }38     return INT_MIN;39 }40 41 int main(){42     vector<int> v;43     v.push_back(1);44     v.push_back(2);45     v.push_back(3);46     v.push_back(2);47     v.push_back(1);48     cout<<findcrest(v)<<endl;49     return 0;50 }

 

九章演算法--尋找數組波峰

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.