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