forked from TheAlgorithms/Java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNearestElement.java
More file actions
73 lines (65 loc) · 2.61 KB
/
NearestElement.java
File metadata and controls
73 lines (65 loc) · 2.61 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
package com.thealgorithms.datastructures.stacks;
import java.util.Stack;
import java.util.Arrays;
public final class NearestElement {
private NearestElement() {}
public static int[] nearestGreaterToRight(int[] arr) {
int n = arr.length;
int[] result = new int[n];
Stack<Integer> indexStack = new Stack<>();
for (int i = n - 1; i >= 0; i--) {
while (!indexStack.isEmpty() && arr[i] >= arr[indexStack.peek()]) {
indexStack.pop();
}
result[i] = indexStack.isEmpty() ? -1 : arr[indexStack.peek()];
indexStack.push(i);
}
return result;
}
public static int[] nearestGreaterToLeft(int[] arr) {
int n = arr.length;
int[] result = new int[n];
Stack<Integer> indexStack = new Stack<>();
for (int i = 0; i < n; i++) {
while (!indexStack.isEmpty() && arr[i] >= arr[indexStack.peek()]) {
indexStack.pop();
}
result[i] = indexStack.isEmpty() ? -1 : arr[indexStack.peek()];
indexStack.push(i);
}
return result;
}
public static int[] nearestSmallerToRight(int[] arr) {
int n = arr.length;
int[] result = new int[n];
Stack<Integer> indexStack = new Stack<>();
for (int i = n - 1; i >= 0; i--) {
while (!indexStack.isEmpty() && arr[i] <= arr[indexStack.peek()]) {
indexStack.pop();
}
result[i] = indexStack.isEmpty() ? -1 : arr[indexStack.peek()];
indexStack.push(i);
}
return result;
}
public static int[] nearestSmallerToLeft(int[] arr) {
int n = arr.length;
int[] result = new int[n];
Stack<Integer> indexStack = new Stack<>();
for (int i = 0; i < n; i++) {
while (!indexStack.isEmpty() && arr[i] <= arr[indexStack.peek()]) {
indexStack.pop();
}
result[i] = indexStack.isEmpty() ? -1 : arr[indexStack.peek()];
indexStack.push(i);
}
return result;
}
public static void main(String[] args) {
int[] sampleArray = {4, 5, 2, 10, 8};
System.out.println("Nearest Greater to Right: " + Arrays.toString(nearestGreaterToRight(sampleArray)));
System.out.println("Nearest Greater to Left: " + Arrays.toString(nearestGreaterToLeft(sampleArray)));
System.out.println("Nearest Smaller to Right: " + Arrays.toString(nearestSmallerToRight(sampleArray)));
System.out.println("Nearest Smaller to Left: " + Arrays.toString(nearestSmallerToLeft(sampleArray)));
}
}