File tree Expand file tree Collapse file tree 1 file changed +14
-25
lines changed
Expand file tree Collapse file tree 1 file changed +14
-25
lines changed Original file line number Diff line number Diff line change 11class MaxStack {
2- private Stack <Integer > st , maxSt ;
2+ private Deque <Integer > dq ;
3+ private PriorityQueue <Integer > pq ;
34
45 public MaxStack () {
5- st = new Stack <>();
6- maxSt = new Stack <>();
6+ dq = new ArrayDeque <>();
7+ pq = new PriorityQueue <>(Collections . reverseOrder () );
78 }
89
910 public void push (int x ) {
10- int max = maxSt .isEmpty () ? Integer .MIN_VALUE : maxSt .peek ();
11- max = Math .max (max , x );
12-
13- st .push (x );
14- maxSt .push (max );
11+ dq .offerLast (x );
12+ pq .offer (x );
1513 }
1614
1715 public int pop () {
18- maxSt .pop ();
19- return st .pop ();
16+ int x = dq .pollLast ();
17+ pq .remove (x );
18+ return x ;
2019 }
2120
2221 public int top () {
23- return st . peek ();
22+ return dq . peekLast ();
2423 }
2524
2625 public int peekMax () {
27- return maxSt .peek ();
26+ return pq .peek ();
2827 }
2928
3029 public int popMax () {
31- int max = peekMax ();
32-
33- Stack <Integer > buffer = new Stack <>();
34-
35- while (top () != max ) {
36- buffer .push (pop ());
37- }
38- pop ();
39- while (!buffer .isEmpty ()) {
40- push (buffer .pop ());
41- }
42-
43- return max ;
30+ int x = pq .poll ();
31+ dq .removeLastOccurrence (x );
32+ return x ;
4433 }
4534}
You can’t perform that action at this time.
0 commit comments