Problem Summary
A is an array with N integers which has the following features:
- The numbers in adjacent positions are different.
- A[0] < A[1] && A[N - 2] > A[N - 1].
We define a position P is a peak if: A[P] > A[P-1] && A[P] > A[P+1]
Find a peak element in this array.
Solution
The O(N) solution is trivial. But can we solve this with a time complexity of O(logN)?
We can think of binary search immediately. The key is whether we can rule out half the indices each time. When we find A[mid]A[mid+1], we can toss out [mid+1,right].
In this way, we can reduce the time complexity to O(logN).
Code
|
|