[InterviewBit] Find a peak element

Find a peak element

  • Time :
  • Space :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
int Solution::solve(vector<int> &A) {
if(A.size() == 0) return A[0];
int l = 0, r = A.size() - 1;
while(l <= r) {
int m = l + (r - l) / 2;
if(m == 0) return A[0] > A[1] ? A[0] : A[1];
if(m == A.size() - 1) return A[A.size() - 1] > A[A.size() - 2] ? A[A.size() - 1] : A[A.size() - 2];
if(A[m-1] < A[m] and A[m] > A[m+1]) return A[m];
if(A[m] < A[m + 1]) l = m + 1;
else r = m - 1;
}
return -1;
}

Author: Song Hayoung
Link: https://songhayoung.github.io/2022/10/26/PS/interviewbit/find-a-peak-element/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.