-
Notifications
You must be signed in to change notification settings - Fork 0
/
012. 带最小值操作的栈.cpp
105 lines (101 loc) · 2.22 KB
/
012. 带最小值操作的栈.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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
class MinStack {
public:
/*
* @param a: An integer
*/
MinStack() {
// do intialization if necessary
}
/* 一般的方法(效率低)
stack<int> s1,s2,s3;
void push(int number) {
// write your code here
s1.push(number);
if(s3.empty()) s3.push(number);
else
{
if(number<=s3.top()) s3.push(number);
else
{
do
{
s2.push(s3.top());
s3.pop();
}while(!s3.empty() && number>s3.top());
s3.push(number);
while(!s2.empty())
{
s3.push(s2.top());
s2.pop();
}
}
}
}
int pop() {
// write your code here
int val = s1.top();
s1.pop();
while(!s3.empty())
{
if(val == s3.top())
{
s3.pop();
break;
}
else
{
s2.push(s3.top());
s3.pop();
}
}
while(!s2.empty())
{
s3.push(s2.top());
s2.pop();
}
return val;
}
int min() {
// write your code here
return s3.top();
}
*/
stack<int> s1,s2;
/*
* @param number: An integer
* @return: nothing
*/
void push(int number) {
// write your code here
s1.push(number);
if(s2.size()<=0 || s2.top() >= number)
s2.push(number);
else
s2.push(s2.top());
}
/*
* @param a: An integer
* @return: An integer
*/
int pop() {
// write your code here
if(s1.size()>0 && s2.size()>0)
{
int val = s1.top();
s1.pop();
s2.pop();
return val;
}
return 0;
}
/*
* @param a: An integer
* @return: An integer
*/
int min() {
// write your code here
if(s1.size()>0 && s2.size()>0)
return s2.top();
return 0;
}
};