Skip to content

Commit bdc6cd3

Browse files
add: 增加最小栈
1 parent fa8f033 commit bdc6cd3

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed

src/202308/stack/最小栈.ts

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
/**
2+
设计一个支持 push ,pop ,top 操作,并能在常数时间内检索到最小元素的栈。
3+
实现 MinStack 类:
4+
MinStack() 初始化堆栈对象。
5+
void push(int val) 将元素val推入堆栈。
6+
void pop() 删除堆栈顶部的元素。
7+
int top() 获取堆栈顶部的元素。
8+
int getMin() 获取堆栈中的最小元素。
9+
* */
10+
11+
class MinStack {
12+
protected Stack:number[] = []
13+
protected MinStack:number[] = []
14+
15+
push(val: number): void {
16+
this.Stack.push(val)
17+
this.MinStack.push(Math.min(val, this.getMin ?? Infinity))
18+
}
19+
pop(): void {
20+
this.Stack.pop()
21+
this.MinStack.pop()
22+
}
23+
top(): number {
24+
return this.Stack[this.Stack.length - 1]
25+
}
26+
getMin(): number {
27+
return this.MinStack[this.MinStack.length - 1]
28+
}
29+
}

0 commit comments

Comments
 (0)