44import java .util .ArrayDeque ;
55
66/**
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:
88 * When larger objects pushed to the queue are able to replace and represent smaller objects that come before it.
99 * Callable methods are:
1010 * isEmpty()
2020 * 4 2 [1, 2] #2->1 [5, 3, 2] 2 kick out 1 #2->3
2121 * 5 4 [1, 2, 4] #4->2 [5,4] 4 kick out 2, 3 #4->2
2222 */
23+
2324public 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
2526
2627 /**
2728 * Checks if queue is empty.
@@ -37,12 +38,10 @@ public boolean isEmpty() {
3738 */
3839 public void push (T obj ) {
3940 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.
4443 }
45- dq .offerLast (new Pair < T >( obj , count ) );
44+ dq .offerLast (obj );
4645 }
4746
4847 /**
@@ -53,7 +52,7 @@ public T max() {
5352 if (isEmpty ()) {
5453 return null ;
5554 }
56- return dq .peek (). value ;
55+ return dq .peek ();
5756 }
5857
5958 /**
@@ -64,26 +63,6 @@ public T pop() {
6463 if (dq .isEmpty ()) {
6564 return null ;
6665 }
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
8867 }
8968}
0 commit comments