Input: mountain =[2,4,4]Output: []Explanation: mountain[0] and mountain[2] can not be a peak because they are first and last elements of the array.mountain[1] also can not be a peak because it is not strictly greater than mountain[2].So the answer is[].
Input: mountain =[1,4,3,8,5]Output: [1,3]Explanation: mountain[0] and mountain[4] can not be a peak because they are first and last elements of the array.mountain[2] also can not be a peak because it is not strictly greater than mountain[3] and mountain[1].But mountain [1] and mountain[3] are strictly greater than their neighboring elements.So the answer is[1,3].
A peak is an element that is strictly greater than its neighbors. Since the first and last elements cannot be peaks, we only need to check elements from index 1 to n-2.
classSolution {
public List<Integer>findPeaks(int[] mountain) {
List<Integer> ans =new ArrayList<>();
int n = mountain.length;
for (int i = 1; i + 1 < n; ++i) {
if (mountain[i]> mountain[i-1]&& mountain[i]> mountain[i+1])
ans.add(i);
}
return ans;
}
}
1
2
3
4
5
6
7
8
9
10
classSolution {
funfindPeaks(mountain: IntArray): List<Int> {
val ans = mutableListOf<Int>()
for (i in1 until mountain.size - 1) {
if (mountain[i] > mountain[i-1] && mountain[i] > mountain[i+1])
ans.add(i)
}
return ans
}
}
1
2
3
4
5
6
7
8
classSolution:
deffindPeaks(self, mountain: list[int]) -> list[int]:
n = len(mountain)
ans = []
for i in range(1, n-1):
if mountain[i] > mountain[i-1] and mountain[i] > mountain[i+1]:
ans.append(i)
return ans
1
2
3
4
5
6
7
8
9
10
11
12
impl Solution {
pubfnfind_peaks(mountain: Vec<i32>) -> Vec<i32> {
let n = mountain.len();
letmut ans =vec![];
for i in1..n-1 {
if mountain[i] > mountain[i-1] && mountain[i] > mountain[i+1] {
ans.push(i asi32);
}
}
ans
}
}