File tree Expand file tree Collapse file tree 1 file changed +86
-0
lines changed
app/src/main/java/com/zhxh/codeproj/leetcode/vip200 Expand file tree Collapse file tree 1 file changed +86
-0
lines changed Original file line number Diff line number Diff line change
1
+ package com .zhxh .codeproj .leetcode .vip200 ;
2
+
3
+ import java .util .Stack ;
4
+
5
+ /*
6
+ 716.最大栈
7
+
8
+ 设计一个最大栈,支持 push、pop、top、peekMax 和 popMax 操作。
9
+
10
+ push(x) -- 将元素 x 压入栈中。
11
+ pop() -- 移除栈顶元素并返回这个值。
12
+ top() -- 返回栈顶元素。
13
+ peekMax() -- 返回栈中最大元素。
14
+ popMax() -- 返回栈中最大的元素,并将其删除。如果有多个最大元素,只要删除最靠近栈顶的那个。
15
+
16
+ 样例 1:
17
+
18
+ MaxStack stack = new MaxStack();
19
+ stack.push(5);
20
+ stack.push(1);
21
+ stack.push(5);
22
+ stack.top(); -> 5
23
+ stack.popMax(); -> 5
24
+ stack.top(); -> 1
25
+ stack.peekMax(); -> 5
26
+ stack.pop(); -> 1
27
+ stack.top(); -> 5
28
+
29
+ 注释:
30
+
31
+ -1e7 <= x <= 1e7
32
+ 操作次数不会超过 10000。
33
+ 当栈为空的时候不会出现后四个操作。
34
+ */
35
+ public class LeetCode716 {
36
+ public static void main (String [] args ) {
37
+ MaxStack stack = new MaxStack ();
38
+ stack .push (5 );
39
+ stack .push (1 );
40
+ stack .push (5 );
41
+ stack .top ();
42
+ stack .popMax ();
43
+ stack .top ();
44
+ stack .peekMax ();
45
+ stack .pop ();
46
+ stack .top ();
47
+ }
48
+
49
+ static class MaxStack {
50
+ Stack <Integer > stack ;
51
+ Stack <Integer > maxStack ;
52
+
53
+ public MaxStack () {
54
+ stack = new Stack ();
55
+ maxStack = new Stack ();
56
+ }
57
+
58
+ public void push (int x ) {
59
+ int max = maxStack .isEmpty () ? x : maxStack .peek ();
60
+ maxStack .push (max > x ? max : x );
61
+ stack .push (x );
62
+ }
63
+
64
+ public int pop () {
65
+ maxStack .pop ();
66
+ return stack .pop ();
67
+ }
68
+
69
+ public int top () {
70
+ return stack .peek ();
71
+ }
72
+
73
+ public int peekMax () {
74
+ return maxStack .peek ();
75
+ }
76
+
77
+ public int popMax () {
78
+ int max = peekMax ();
79
+ Stack <Integer > buffer = new Stack ();
80
+ while (top () != max ) buffer .push (pop ());
81
+ pop ();
82
+ while (!buffer .isEmpty ()) push (buffer .pop ());
83
+ return max ;
84
+ }
85
+ }
86
+ }
You can’t perform that action at this time.
0 commit comments