Update MultiplePeakFinder.java

This commit is contained in:
Imran Alam 2024-03-01 13:16:27 +05:30 committed by GitHub
parent e62e1d88e6
commit dfe98f6202
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
1 changed files with 12 additions and 12 deletions

View File

@ -12,11 +12,11 @@ public class MultiplePeakFinder {
if (arr == null || arr.length == 0) {
return peaks;
}
findPeakElement(arr, 0, arr.length - 1, peaks);
findPeakElements(arr, 0, arr.length - 1, peaks, arr.length);
return peaks;
}
private static void findPeakElement(int[] arr, int low, int high, List<Integer> peaks) {
private static void findPeakElements(int[] arr, int low, int high, List<Integer> peaks, int length) {
if (low > high) {
return;
@ -24,17 +24,17 @@ public class MultiplePeakFinder {
int mid = low + (high - low) / 2;
if ((mid == 0 || arr[mid] >= arr[mid - 1]) && (mid == arr.length - 1 || arr[mid] >= arr[mid + 1])) {
boolean isPeak = (mid == 0 || arr[mid] > arr[mid - 1]) && (mid == length - 1 || arr[mid] > arr[mid + 1]);
boolean isFirstInSequence = mid > 0 && arr[mid] == arr[mid - 1] && arr[mid] > arr[mid + 1];
if (isPeak || isFirstInSequence) {
if (!peaks.contains(arr[mid])) {
peaks.add(arr[mid]);
}
if (mid > 0) {
findPeakElement(arr, low, mid - 1, peaks);
}
if (mid < arr.length - 1) {
findPeakElement(arr, mid + 1, high, peaks);
}
findPeakElements(arr, low, mid - 1, peaks, length);
findPeakElements(arr, mid + 1, high, peaks, length);
}
}