Chapter 9 algorithm -- Searching for Array peaks

Source: Internet
Author: User

Question Description: An array a [1 .. n]. Assume that no adjacent two numbers in the array are equal to each other and meet the conditions of a [1] <A [2], a [n-1]> A [n]. A [I] is called a wave crest, when and only when a [I]> A [I-1] And a [I]> A [I + 1]. Find a wave crest in the array. Suppose there are adjacent equal numbers in the array. How can this problem be solved?

Find a peak in the two ways,

If the array has adjacent equal elements, it must be O (n)

1 /************************************** * *********************************** 2> File Name: arraywavecrest. CPP 3> author: zhoukang1991 4> mail: [email protected] 5> created time: friday, 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}

 

Chapter 9 algorithm -- Searching for Array peaks

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.