Leetcode-剑指Offer30

Kelvin

保存差值栈

剑指 Offer 30. 包含min函数的栈

min_x: 栈中最小值
栈diff_stack: 元素与最小值的差

如果diff_stack.top()<0,栈顶元素位min_x,否则栈顶元素为min_x+diff_stack.top().
push方法中先计算diff再更新min_x是建立之前栈最小值与当前栈最小值的联系.
需要注意的是两个int类型数相减可能越界,需要用long long保存差值.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
class MinStack {
public:
stack<long long> diff_stack;
int min_x = 0;
MinStack() {

}

void push(int x) {
if(diff_stack.size()==0){
diff_stack.push(0L);
min_x = x;
}else{
long long diff = (long long)x-min_x;
diff_stack.push(diff);
if(diff<0) min_x = x;
}
}

void pop() {
if(diff_stack.top()<0) min_x = min_x-diff_stack.top();
diff_stack.pop();
}

int top() {
return diff_stack.top()<0?min_x:diff_stack.top()+min_x;
}

int min() {
return min_x;
}
};
  • Title: Leetcode-剑指Offer30
  • Author: Kelvin
  • Created at: 2023-05-11 20:10:33
  • Updated at: 2023-01-16 22:02:42
  • Link: https://yanwc.com/2023/05/11/2023-01-14-leetcode-offer30/
  • License: This work is licensed under CC BY-NC-SA 4.0.
On this page
Leetcode-剑指Offer30