4
4
import java .util .ArrayDeque ;
5
5
6
6
/**
7
- * Implementation of a non-increasing monotonic queue for certain (but common) use case:
7
+ * Implementation of a non-increasing (decreasing) monotonic queue for certain (but common) use case:
8
8
* When larger objects pushed to the queue are able to replace and represent smaller objects that come before it.
9
9
* Callable methods are:
10
10
* isEmpty()
20
20
* 4 2 [1, 2] #2->1 [5, 3, 2] 2 kick out 1 #2->3
21
21
* 5 4 [1, 2, 4] #4->2 [5,4] 4 kick out 2, 3 #4->2
22
22
*/
23
+
23
24
public class MonotonicQueue <T extends Comparable <T >> {
24
- private Deque <Pair < T > > dq = new ArrayDeque <>(); // or LinkedList
25
+ private Deque <T > dq = new ArrayDeque <>(); // or LinkedList
25
26
26
27
/**
27
28
* Checks if queue is empty.
@@ -37,12 +38,10 @@ public boolean isEmpty() {
37
38
*/
38
39
public void push (T obj ) {
39
40
Integer count = 0 ;
40
- while (!dq .isEmpty () && obj .compareTo (dq .peekLast ().value ) >= 0 ) {
41
- Pair <T > popped = dq .pollLast ();
42
- // accumulate count of objects that were popped to maintain the non-increasing property
43
- count += 1 + popped .countDeleted ;
41
+ while (!dq .isEmpty () && obj .compareTo (dq .peekLast ()) > 0 ) {
42
+ dq .pollLast (); // Removes elements that do not conform the non-increasing sequence.
44
43
}
45
- dq .offerLast (new Pair < T >( obj , count ) );
44
+ dq .offerLast (obj );
46
45
}
47
46
48
47
/**
@@ -53,7 +52,7 @@ public T max() {
53
52
if (isEmpty ()) {
54
53
return null ;
55
54
}
56
- return dq .peek (). value ;
55
+ return dq .peek ();
57
56
}
58
57
59
58
/**
@@ -64,26 +63,6 @@ public T pop() {
64
63
if (dq .isEmpty ()) {
65
64
return null ;
66
65
}
67
- Pair <T > node = dq .peek ();
68
- if (node .countDeleted > 0 ) {
69
- node .countDeleted -= 1 ;
70
- return node .value ;
71
- }
72
- dq .poll ();
73
- return node .value ;
74
- }
75
-
76
- /**
77
- * Node class that is represented as a pair.
78
- * Tracks the deleted count and the value to be wrapped.
79
- */
80
- private static class Pair <T > {
81
- private T value ;
82
- private Integer countDeleted ;
83
-
84
- private Pair (T val , Integer count ) {
85
- this .value = val ;
86
- this .countDeleted = count ;
87
- }
66
+ return dq .poll (); // Returns & remove head of deque
88
67
}
89
68
}
0 commit comments