Skip to content

Commit de0b673

Browse files
authored
feat: add solutions to lcci problems: No.03.05,03.06 (doocs#2533)
* No.03.05.Sort of Stacks * No.03.06.Animal Shelter
1 parent 9391bf2 commit de0b673

17 files changed

+891
-561
lines changed

lcci/03.05.Sort of Stacks/README.md

+150-115
Original file line numberDiff line numberDiff line change
@@ -33,64 +33,85 @@
3333

3434
## 解法
3535

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$ 为栈中元素的个数。
3749

3850
<!-- tabs:start -->
3951

4052
```python
4153
class SortedStack:
54+
4255
def __init__(self):
43-
self.s = []
56+
self.stk = []
4457

4558
def push(self, val: int) -> None:
4659
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())
5265

5366
def pop(self) -> None:
5467
if not self.isEmpty():
55-
self.s.pop()
68+
self.stk.pop()
5669

5770
def peek(self) -> int:
58-
return -1 if self.isEmpty() else self.s[-1]
71+
return -1 if self.isEmpty() else self.stk[-1]
5972

6073
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()
6283
```
6384

6485
```java
6586
class SortedStack {
66-
private Stack<Integer> s;
87+
private Deque<Integer> stk = new ArrayDeque<>();
88+
6789
public SortedStack() {
68-
s = new Stack<>();
6990
}
7091

7192
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());
7596
}
76-
s.push(val);
97+
stk.push(val);
7798
while (!t.isEmpty()) {
78-
s.push(t.pop());
99+
stk.push(t.pop());
79100
}
80101
}
81102

82103
public void pop() {
83104
if (!isEmpty()) {
84-
s.pop();
105+
stk.pop();
85106
}
86107
}
87108

88109
public int peek() {
89-
return isEmpty() ? -1 : s.peek();
110+
return isEmpty() ? -1 : stk.peek();
90111
}
91112

92113
public boolean isEmpty() {
93-
return s.isEmpty();
114+
return stk.isEmpty();
94115
}
95116
}
96117

@@ -104,74 +125,129 @@ class SortedStack {
104125
*/
105126
```
106127

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+
107175
```go
108176
type SortedStack struct {
109-
data []int
177+
stk []int
110178
}
111179

112180
func Constructor() SortedStack {
113-
return SortedStack{make([]int, 0)}
181+
return SortedStack{}
114182
}
115183

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]
121189
}
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])
126193
}
127194
}
128195

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]
132199
}
133200
}
134201

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
138205
}
139-
return -1
206+
return this.stk[len(this.stk)-1]
140207
}
141208

142-
func (s *SortedStack) IsEmpty() bool {
143-
return len(s.data) == 0
209+
func (this *SortedStack) IsEmpty() bool {
210+
return len(this.stk) == 0
144211
}
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+
*/
145221
```
146222

147223
```ts
148224
class SortedStack {
149-
stack: number[];
150-
constructor() {
151-
this.stack = [];
152-
}
225+
private stk: number[] = [];
226+
constructor() {}
153227

154228
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()!);
158232
}
159-
this.stack.push(val);
233+
this.stk.push(val);
160234
while (t.length > 0) {
161-
this.stack.push(t.pop());
235+
this.stk.push(t.pop()!);
162236
}
163237
}
164238

165239
pop(): void {
166-
this.stack.pop();
240+
if (!this.isEmpty()) {
241+
this.stk.pop();
242+
}
167243
}
168244

169245
peek(): number {
170-
return this.isEmpty() ? -1 : this.stack[this.stack.length - 1];
246+
return this.isEmpty() ? -1 : this.stk.at(-1)!;
171247
}
172248

173249
isEmpty(): boolean {
174-
return this.stack.length == 0;
250+
return this.stk.length === 0;
175251
}
176252
}
177253

@@ -187,39 +263,46 @@ class SortedStack {
187263

188264
```rust
189265
use std::collections::VecDeque;
266+
190267
struct SortedStack {
191-
stack: VecDeque<i32>,
268+
stk: VecDeque<i32>,
192269
}
193270

194-
/**
195-
* `&self` means the method takes an immutable reference.
196-
* If you need a mutable reference, change it to `&mut self` instead.
197-
*/
198271
impl SortedStack {
199272
fn new() -> Self {
200-
Self { stack: VecDeque::new() }
273+
SortedStack {
274+
stk: VecDeque::new(),
275+
}
201276
}
202277

203278
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);
207291
}
208-
let t = self.stack.pop_back().unwrap();
209-
self.push(val);
210-
self.stack.push_back(t);
211292
}
212293

213294
fn pop(&mut self) {
214-
self.stack.pop_back();
295+
if !self.is_empty() {
296+
self.stk.pop_back();
297+
}
215298
}
216299

217300
fn peek(&self) -> i32 {
218-
*self.stack.back().unwrap_or(&-1)
301+
if self.is_empty() { -1 } else { *self.stk.back().unwrap() }
219302
}
220303

221304
fn is_empty(&self) -> bool {
222-
self.stack.is_empty()
305+
self.stk.is_empty()
223306
}
224307
}/**
225308
* Your SortedStack object will be instantiated and called as such:
@@ -233,52 +316,4 @@ impl SortedStack {
233316

234317
<!-- tabs:end -->
235318

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-
284319
<!-- end -->

0 commit comments

Comments
 (0)