-
Notifications
You must be signed in to change notification settings - Fork 0
/
offer_59
84 lines (65 loc) · 1.74 KB
/
offer_59
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
//面试题59:队列的最大值
//题目1:滑动窗口的最大值
vector<int> maxInWindows(const vector<int>& num,unsigned int size)
{
vector<int> maxInWindows;
if(num.size()>=size&&size>=1){
deque<int> index;
for(unsigned int i=0;i<size;++i){
while(!index.empty()&&num[i]>=num[index.back()])
index.pop_back()'
index.push_back();
}
for(unsigned int i=size;i<num.size();++i){
maxInWindows.push_back(num[index.front()]);
while(!index.empty()&&num[i]>=num[index.back()])
index.pop_back();
if(!index.empty() && index.front()<=(int)(i-size))
index.pop_back();
index.push_back();
}
maxInWindows.push_back(num[index.front()]);
}
return maxInWindows;
}
//题目2:队列的最大值
template<class T>
class QueueWithMax
{
public:
QueueWithMax():currentIndex(0)
{
}
void push_back(T number)
{
while(!maximums.empty()&&number>=maximums.back().number)
maximums.pop_back();
InternalData internalData={number,currentIndex};
data.push_back(internalData);
maximums.push_back(internalData);
++currentIndex;
}
void pop_front()
{
if(maximums.empty())
throw new exception("queue is empty");
if(maximums.front().index==data.front().index)
maximums.pop_front();
data.pop_front();
}
T max() const
{
if(maximums.empty())
throw new exception("queue is empty");
return maximums.front().number;
}
private:
struct InternalData
{
T number;
int index;
};
deque<IntenalData> data;
deque<IntenalData> maximums;
int currentIndex;
}