-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFind Peak Element.cpp
91 lines (56 loc) · 1.96 KB
/
Find Peak Element.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
// Find Peak Element
// Easy
// 39/40
// Average time to solve is 15m
// Contributed by
// 181 upvotes
// Asked in companies
// Problem statement
// You are given an array 'arr' of length 'n'. Find the index(0-based) of a peak element in the array. If there are multiple peak numbers, return the index of any peak number.
// Peak element is defined as that element that is greater than both of its neighbors. If 'arr[i]' is the peak element, 'arr[i - 1]' < 'arr[i]' and 'arr[i + 1]' < 'arr[i]'.
// Assume 'arr[-1]' and 'arr[n]' as negative infinity.
// Note:
// 1. There are no 2 adjacent elements having same value (as mentioned in the constraints).
// 2. Do not print anything, just return the index of the peak element (0 - indexed).
// 3. 'True'/'False' will be printed depending on whether your answer is correct or not.
// Example:
// Input: 'arr' = [1, 8, 1, 5, 3]
// Output: 3
// Explanation: There are two possible answers. Both 8 and 5 are peak elements, so the correct answers are their positions, 1 and 3.
// Detailed explanation ( Input/output format, Notes, Images )
// Sample Input 1:
// 5
// 1 8 1 5 3
// Expected Answer:
// 1
// Output on Console:
// True
// Explanation of sample input 1 :
// There are two possible answers. Both 8 and 5 are peak elements, so the correct answers are their positions, 1 and 3. Any of these 2 numbers will print 'True'.
// Sample Input 2:
// 3
// 1 2 1
// Expected Answer:
// 1
// Output on Console:
// True
// Expected time complexity:
// The expected time complexity is O(log 'n').
// Constraints:
// 1 <= 'n' <= 10^5
// 1 <= 'arr[i]' <= 10^5
// 'arr[i]' != 'arr[i + 1]' for all 'i' in range 0 <= 'i' < 'n' - 1
int findPeakElement(vector<int> &arr) {
// Write your code here
int i=0;
int j=arr.size()-1;
while(i<j){
int mid = i+(j-i)/2;
if(arr[mid]<arr[mid+1]){
i=mid+1;
}else{
j=mid;
}
}
return i;
}