-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path155.最小栈.cpp
67 lines (61 loc) · 1.14 KB
/
155.最小栈.cpp
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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
/*
* @lc app=leetcode.cn id=155 lang=cpp
*
* [155] 最小栈
*/
#include "a_header.h"
// @lc code=start
class MinStack
{
private:
int index;
int nums;
vector<pair<int, int>> stack;
public:
MinStack()
{
nums = 0;
index = -1;
}
void push(int val)
{
nums++;
stack.push_back(make_pair(index, val));
index = index == -1 ? 0 : (stack[index].second < val ? index : nums - 1);
}
void pop()
{
if (nums > 0)
{
if (nums == index + 1)
{
index = stack[index].first;
}
nums--;
stack.pop_back();
}
}
int top()
{
if (nums > 0)
return stack[nums - 1].second;
else
return INT_MAX;
}
int getMin()
{
if (nums > 0)
return stack[index].second;
else
return INT_MAX;
}
};
/**
* Your MinStack object will be instantiated and called as such:
* MinStack* obj = new MinStack();
* obj->push(val);
* obj->pop();
* int param_3 = obj->top();
* int param_4 = obj->getMin();
*/
// @lc code=end