-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathMinStack1.h
106 lines (86 loc) · 2.24 KB
/
MinStack1.h
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
106
/***************************************************************************
* File:MinStack.h
* @author:asuwill([email protected])
* @date 2014-03-04
*
* A LIFO stack class that supports O(1) push, pop, and find-min. Here, the
* find-min operation returns (but does not remove) the minimum value in the
* stack. This sort of stack is often used as a subroutine in other problems.
* It can be used to construct a queue with equivalent properties by
* using one of the many stack-to-queue constructions, for example.
*
* the basic idea here is: use extra space to store index to min value
2.设计包含min函数的栈。
定义栈的数据结构,要求添加一个min函数,能够得到栈的最小元素。
要求函数min、push以及pop的时间复杂度都是O(1)。
*/
#ifndef MIN_STACK_H
#define MIN_STACK_H
#include<vector> // use as stack
#include<functional> // std::less
template<typename T,
typename Comparator = std::less<T> >
class MinStack
{
public:
explicit MinStack(Comparator=Comparator());
void push(const T& v);
void pop();
const T& top() const;
const T& min() const;
bool empty() const;
size_t size() const;
private:
std::vector<T> m_vStack; //store value
std::vector<int> m_iStack;//store index to min
Comparator m_comp;
};
template<typename T,typename Comparator>
MinStack<T,Comparator>::MinStack(Comparator c)
:m_vStack(),m_iStack(),m_comp(c)
{
}
template<typename T,typename Comparator>
bool MinStack<T,Comparator>::empty()const
{
return m_vStack.empty();
}
template<typename T,typename Comparator>
size_t MinStack<T,Comparator>::size()const
{
return m_vStack.size();
}
template<typename T,typename Comparator>
void MinStack<T,Comparator>::pop()
{
m_vStack.pop_back();
m_iStack.pop_back();
}
template<typename T,typename Comparator>
const T& MinStack<T,Comparator>::top() const
{
return m_vStack.back();
}
template<typename T,typename Comparator>
const T& MinStack<T,Comparator>::min() const
{
return m_vStack[m_iStack.back()];
}
template<typename T,typename Comparator>
void MinStack<T,Comparator>::push(const T& v)
{
if(empty())
{
m_vStack.push_back(v);
m_iStack.push_back(0);
}
else
{
size_t min_index = m_iStack.back();
if(m_comp(v,min()))
min_index = m_vStack.size();
m_vStack.push_back(v);
m_iStack.push_back(min_index);
}
}
#endif