Find Peak Element
Given an array of integers where each element represents the altitude at that index, your task is to return the index of any peak element. A peak element is defined as an element that is greater than its neighbors. Note that if the array length is 1, or the peak occurs at the boundaries of the array (first or last index), consider only one neighbor for comparison.
[ 1 ]
Explanation. With only one element, that element is trivially a peak element.
[ 1, 3, 2, 1 ]
Explanation. Element at index 1 is greater than its neighbors (1 and 2).
[ 5, 4, 3, 2, 1 ]
Explanation. The first element is a peak as it is greater than its only neighbor.
[ 1, 2, 3, 4, 5 ]
Explanation. The last element is a peak as it is greater than its only neighbor.
[ 2, 4, 6, 5, 7, 8, 7 ]
Explanation. Element at index 2 is a peak because it's greater than its neighbors (4 and 5). Alternatively, index 5 could also be accepted as a valid peak.
Follow-up: How would you modify your solution if you need to find all the peaks?
1. The array will contain at least one element.\n2. If there are multiple peak elements, returning the index of any one of them is accepted.\n3. The array may contain duplicate elements.
- Views
- 2