33
33
34
34
## 解法
35
35
36
- ### 方法一
36
+ ### 方法一:栈 + 辅助栈
37
+
38
+ 我们定义一个栈 $stk$,用于存放元素。
39
+
40
+ 在 ` push ` 操作中,我们定义一个辅助栈 $t$,用于存放 $stk$ 中比当前元素小的元素。我们将 $stk$ 中比当前元素小的元素全部弹出并存放到 $t$ 中,然后将当前元素压入 $stk$,最后将 $t$ 中的元素全部弹出并压入 $stk$。时间复杂度 $O(n)$。
41
+
42
+ 在 ` pop ` 操作中,我们只需要判断 $stk$ 是否为空,如果不为空,则弹出栈顶元素。时间复杂度 $O(1)$。
43
+
44
+ 在 ` peek ` 操作中,我们只需要判断 $stk$ 是否为空,如果为空则返回 -1,否则返回栈顶元素。时间复杂度 $O(1)$。
45
+
46
+ 在 ` isEmpty ` 操作中,我们只需要判断 $stk$ 是否为空。时间复杂度 $O(1)$。
47
+
48
+ 空间复杂度 $O(n)$,其中 $n$ 为栈中元素的个数。
37
49
38
50
<!-- tabs:start -->
39
51
40
52
``` python
41
53
class SortedStack :
54
+
42
55
def __init__ (self ):
43
- self .s = []
56
+ self .stk = []
44
57
45
58
def push (self , val : int ) -> None :
46
59
t = []
47
- while not self .isEmpty() and self .s [- 1 ] < val:
48
- t.append(self .s .pop())
49
- self .s .append(val)
50
- while len (t) > 0 :
51
- self .s .append(t.pop())
60
+ while self .stk and self .stk [- 1 ] < val:
61
+ t.append(self .stk .pop())
62
+ self .stk .append(val)
63
+ while t :
64
+ self .stk .append(t.pop())
52
65
53
66
def pop (self ) -> None :
54
67
if not self .isEmpty():
55
- self .s .pop()
68
+ self .stk .pop()
56
69
57
70
def peek (self ) -> int :
58
- return - 1 if self .isEmpty() else self .s [- 1 ]
71
+ return - 1 if self .isEmpty() else self .stk [- 1 ]
59
72
60
73
def isEmpty (self ) -> bool :
61
- return len (self .s) == 0
74
+ return not self .stk
75
+
76
+
77
+ # Your SortedStack object will be instantiated and called as such:
78
+ # obj = SortedStack()
79
+ # obj.push(val)
80
+ # obj.pop()
81
+ # param_3 = obj.peek()
82
+ # param_4 = obj.isEmpty()
62
83
```
63
84
64
85
``` java
65
86
class SortedStack {
66
- private Stack<Integer > s;
87
+ private Deque<Integer > stk = new ArrayDeque<> ();
88
+
67
89
public SortedStack () {
68
- s = new Stack<> ();
69
90
}
70
91
71
92
public void push (int val ) {
72
- Stack <Integer > t = new Stack <> ();
73
- while (! isEmpty() && s . peek() < val) {
74
- t. push(s . pop());
93
+ Deque <Integer > t = new ArrayDeque <> ();
94
+ while (! stk . isEmpty() && stk . peek() < val) {
95
+ t. push(stk . pop());
75
96
}
76
- s . push(val);
97
+ stk . push(val);
77
98
while (! t. isEmpty()) {
78
- s . push(t. pop());
99
+ stk . push(t. pop());
79
100
}
80
101
}
81
102
82
103
public void pop () {
83
104
if (! isEmpty()) {
84
- s . pop();
105
+ stk . pop();
85
106
}
86
107
}
87
108
88
109
public int peek () {
89
- return isEmpty() ? - 1 : s . peek();
110
+ return isEmpty() ? - 1 : stk . peek();
90
111
}
91
112
92
113
public boolean isEmpty () {
93
- return s . isEmpty();
114
+ return stk . isEmpty();
94
115
}
95
116
}
96
117
@@ -104,74 +125,129 @@ class SortedStack {
104
125
*/
105
126
```
106
127
128
+ ``` cpp
129
+ class SortedStack {
130
+ public:
131
+ SortedStack() {
132
+ }
133
+
134
+ void push(int val) {
135
+ stack<int> t;
136
+ while (!stk.empty() && stk.top() < val) {
137
+ t.push(stk.top());
138
+ stk.pop();
139
+ }
140
+ stk.push(val);
141
+ while (!t.empty()) {
142
+ stk.push(t.top());
143
+ t.pop();
144
+ }
145
+ }
146
+
147
+ void pop() {
148
+ if (!isEmpty()) {
149
+ stk.pop();
150
+ }
151
+ }
152
+
153
+ int peek() {
154
+ return isEmpty() ? -1 : stk.top();
155
+ }
156
+
157
+ bool isEmpty() {
158
+ return stk.empty();
159
+ }
160
+
161
+ private:
162
+ stack<int > stk;
163
+ };
164
+
165
+ /* *
166
+ * Your SortedStack object will be instantiated and called as such:
167
+ * SortedStack* obj = new SortedStack();
168
+ * obj->push(val);
169
+ * obj->pop();
170
+ * int param_3 = obj->peek();
171
+ * bool param_4 = obj->isEmpty();
172
+ */
173
+ ```
174
+
107
175
``` go
108
176
type SortedStack struct {
109
- data []int
177
+ stk []int
110
178
}
111
179
112
180
func Constructor () SortedStack {
113
- return SortedStack{make ([] int , 0 ) }
181
+ return SortedStack{}
114
182
}
115
183
116
- func (s *SortedStack ) Push (val int ) {
117
- temp := make ([]int , 0 )
118
- for !s. IsEmpty () && s. Peek () < val {
119
- temp = append (temp, s. Peek () )
120
- s. Pop ()
184
+ func (this *SortedStack ) Push (val int ) {
185
+ t := make ([]int , 0 )
186
+ for len (this. stk ) > 0 && this. stk [ len (this. stk )- 1 ] < val {
187
+ t = append (t, this. stk [ len (this. stk )- 1 ] )
188
+ this. stk = this. stk [: len (this. stk )- 1 ]
121
189
}
122
- s.data = append (s.data , val)
123
- for len (temp) > 0 {
124
- s.data = append (s.data , temp[len (temp)-1 ])
125
- temp = temp[:len (temp)-1 ]
190
+ this.stk = append (this.stk , val)
191
+ for i := len (t) - 1 ; i >= 0 ; i-- {
192
+ this.stk = append (this.stk , t[i])
126
193
}
127
194
}
128
195
129
- func (s *SortedStack ) Pop () {
130
- if !s .IsEmpty () {
131
- s. data = s. data [:len (s. data )-1 ]
196
+ func (this *SortedStack ) Pop () {
197
+ if !this .IsEmpty () {
198
+ this. stk = this. stk [:len (this. stk )-1 ]
132
199
}
133
200
}
134
201
135
- func (s *SortedStack ) Peek () int {
136
- if !s .IsEmpty () {
137
- return s. data [ len (s. data )- 1 ]
202
+ func (this *SortedStack ) Peek () int {
203
+ if this .IsEmpty () {
204
+ return - 1
138
205
}
139
- return - 1
206
+ return this. stk [ len (this. stk )- 1 ]
140
207
}
141
208
142
- func (s *SortedStack ) IsEmpty () bool {
143
- return len (s. data ) == 0
209
+ func (this *SortedStack ) IsEmpty () bool {
210
+ return len (this. stk ) == 0
144
211
}
212
+
213
+ /* *
214
+ * Your SortedStack object will be instantiated and called as such:
215
+ * obj := Constructor();
216
+ * obj.Push(val);
217
+ * obj.Pop();
218
+ * param_3 := obj.Peek();
219
+ * param_4 := obj.IsEmpty();
220
+ */
145
221
```
146
222
147
223
``` ts
148
224
class SortedStack {
149
- stack: number [];
150
- constructor () {
151
- this .stack = [];
152
- }
225
+ private stk: number [] = [];
226
+ constructor () {}
153
227
154
228
push(val : number ): void {
155
- let t = [];
156
- while (! this .isEmpty () && this .peek () < val ) {
157
- t .push (this .stack .pop ());
229
+ const t : number [] = [];
230
+ while (this .stk . length > 0 && this .stk . at ( - 1 ) ! < val ) {
231
+ t .push (this .stk .pop ()! );
158
232
}
159
- this .stack .push (val );
233
+ this .stk .push (val );
160
234
while (t .length > 0 ) {
161
- this .stack .push (t .pop ());
235
+ this .stk .push (t .pop ()! );
162
236
}
163
237
}
164
238
165
239
pop(): void {
166
- this .stack .pop ();
240
+ if (! this .isEmpty ()) {
241
+ this .stk .pop ();
242
+ }
167
243
}
168
244
169
245
peek(): number {
170
- return this .isEmpty () ? - 1 : this .stack [ this . stack . length - 1 ] ;
246
+ return this .isEmpty () ? - 1 : this .stk . at ( - 1 ) ! ;
171
247
}
172
248
173
249
isEmpty(): boolean {
174
- return this .stack .length == 0 ;
250
+ return this .stk .length = == 0 ;
175
251
}
176
252
}
177
253
@@ -187,39 +263,46 @@ class SortedStack {
187
263
188
264
``` rust
189
265
use std :: collections :: VecDeque ;
266
+
190
267
struct SortedStack {
191
- stack : VecDeque <i32 >,
268
+ stk : VecDeque <i32 >,
192
269
}
193
270
194
- /**
195
- * `&self` means the method takes an immutable reference.
196
- * If you need a mutable reference, change it to `&mut self` instead.
197
- */
198
271
impl SortedStack {
199
272
fn new () -> Self {
200
- Self { stack : VecDeque :: new () }
273
+ SortedStack {
274
+ stk : VecDeque :: new (),
275
+ }
201
276
}
202
277
203
278
fn push (& mut self , val : i32 ) {
204
- if self . is_empty () || self . peek () > val {
205
- self . stack. push_back (val );
206
- return ;
279
+ let mut t = VecDeque :: new ();
280
+ while let Some (top ) = self . stk. pop_back () {
281
+ if top < val {
282
+ t . push_back (top );
283
+ } else {
284
+ self . stk. push_back (top );
285
+ break ;
286
+ }
287
+ }
288
+ self . stk. push_back (val );
289
+ while let Some (top ) = t . pop_back () {
290
+ self . stk. push_back (top );
207
291
}
208
- let t = self . stack. pop_back (). unwrap ();
209
- self . push (val );
210
- self . stack. push_back (t );
211
292
}
212
293
213
294
fn pop (& mut self ) {
214
- self . stack. pop_back ();
295
+ if ! self . is_empty () {
296
+ self . stk. pop_back ();
297
+ }
215
298
}
216
299
217
300
fn peek (& self ) -> i32 {
218
- * self . stack . back (). unwrap_or ( & - 1 )
301
+ if self . is_empty () { - 1 } else { * self . stk . back (). unwrap () }
219
302
}
220
303
221
304
fn is_empty (& self ) -> bool {
222
- self . stack . is_empty ()
305
+ self . stk . is_empty ()
223
306
}
224
307
}/**
225
308
* Your SortedStack object will be instantiated and called as such:
@@ -233,52 +316,4 @@ impl SortedStack {
233
316
234
317
<!-- tabs:end -->
235
318
236
- ### 方法二
237
-
238
- <!-- tabs:start -->
239
-
240
- ``` ts
241
- class SortedStack {
242
- private stack: number [];
243
-
244
- constructor () {
245
- this .stack = [];
246
- }
247
-
248
- push(val : number ): void {
249
- if (this .isEmpty () || this .peek () > val ) {
250
- this .stack .push (val );
251
- return ;
252
- }
253
-
254
- const tmp = this .stack .pop ();
255
- this .push (val );
256
- this .stack .push (tmp );
257
- }
258
-
259
- pop(): void {
260
- this .stack .pop ();
261
- }
262
-
263
- peek(): number {
264
- return this .stack [this .stack .length - 1 ] ?? - 1 ;
265
- }
266
-
267
- isEmpty(): boolean {
268
- return this .stack .length === 0 ;
269
- }
270
- }
271
-
272
- /**
273
- * Your SortedStack object will be instantiated and called as such:
274
- * var obj = new SortedStack()
275
- * obj.push(val)
276
- * obj.pop()
277
- * var param_3 = obj.peek()
278
- * var param_4 = obj.isEmpty()
279
- */
280
- ```
281
-
282
- <!-- tabs:end -->
283
-
284
319
<!-- end -->
0 commit comments