-
Notifications
You must be signed in to change notification settings - Fork 56
/
Copy pathMinStack.cpp
69 lines (47 loc) · 1.26 KB
/
MinStack.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
/*
https://www.interviewbit.com/problems/min-stack/
Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.
push(x) – Push element x onto stack.
pop() – Removes the element on top of the stack.
top() – Get the top element.
getMin() – Retrieve the minimum element in the stack.
Note that all the operations have to be constant time operations.
Questions to ask the interviewer :
Q: What should getMin() do on empty stack?
A: In this case, return -1.
Q: What should pop do on empty stack?
A: In this case, nothing.
Q: What should top() do on empty stack?
A: In this case, return -1
NOTE : If you are using your own declared global variables, make sure to clear them out in the constructor.
*/
stack<pair<int, int>> st;
MinStack::MinStack()
{
while(!st.empty())
st.pop();
}
void MinStack::push(int x)
{
int mn = st.empty() ? x : min(st.top().second, x);
st.push(make_pair(x, mn));
}
void MinStack::pop()
{
if(!st.empty())
st.pop();
}
int MinStack::top()
{
if(!st.empty())
return st.top().first;
else
return -1;
}
int MinStack::getMin()
{
if(!st.empty())
return st.top().second;
else
return -1;
}