You are given an integer array nums
. A peak element in this array is an element that is greater than its neighbors. For example, in the array [1, 3, 2], 3 is a peak element since it’s greater than both 1 (its left neighbor) and 2 (its right neighbor). You need to write a function findPeaksOut
that returns a list of all the peak elements in the array.
The function signature is:
List<Integer> findPeaksOut(int[] nums)
nums
: If nums[i]
(where i
is the index) is at the boundary (i.e., i == 0
or i == nums.length - 1
), it’s a peak if it is greater than its single neighbor.import java.util.*;
public class FindPeaks {
public static List<Integer> findPeaksOut(int[] nums) {
List<Integer> peaks = new ArrayList<>();
if (nums == null || nums.length == 0) {
return peaks;
}
int n = nums.length;
for (int i = 0; i < n; i++) {
// Check if the current element is a peak
boolean isPeak = false;
if (i == 0) {
// First element peak condition (greater than next element)
if (n == 1 || nums[i] > nums[i + 1]) {
isPeak = true;
}
} else if (i == n - 1) {
// Last element peak condition (greater than previous element)
if (nums[i] > nums[i - 1]) {
isPeak = true;
}
} else {
// Middle elements peak condition (greater than both neighbors)
if (nums[i] > nums[i - 1] && nums[i] > nums[i + 1]) {
isPeak = true;
}
}
if (isPeak) {
peaks.add(nums[i]);
}
}
return peaks;
}
public static void main(String[] args) {
int[] nums1 = {1, 3, 2, 4, 1};
int[] nums2 = {1, 2, 3, 4, 5};
int[] nums3 = {5, 4, 3, 2, 1};
int[] nums4 = {2, 2, 2, 2};
System.out.println(findPeaksOut(nums1)); // Output: [3, 4]
System.out.println(findPeaksOut(nums2)); // Output: [5]
System.out.println(findPeaksOut(nums3)); // Output: [5]
System.out.println(findPeaksOut(nums4)); // Output: []
}
}
n
is the number of elements in the array. This is because we are iterating through the array once to check each element.k
is the number of peak elements found.This algorithm efficiently finds all the peak elements within a single pass through the array.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?