0%

栈与队列

栈与队列相互实现

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
//栈实现队列
class MyQueue {
public:
MyQueue() : s_in() , s_out()
{}

void push(int x) {
s_in.push(x);
}

int pop() {
if(s_out.empty())
while(!s_in.empty())
{
s_out.push(s_in.top());
s_in.pop();
}
int tmp=s_out.top();
s_out.pop();
return tmp;
}

int peek() {
int tmp=this->pop();
s_out.push(tmp);
return tmp;
}

bool empty() {
return s_in.empty() && s_out.empty();
}
private:
stack<int> s_in;
stack<int> s_out;
};
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
//队列实现栈
class MyStack {
public:
MyStack() : q()
{}

void push(int x) {
q.push(x);
}

int pop() {
int t=q.size()-1;
while(t--)
{
q.push(q.front());
q.pop();
}
int tmp=q.front();
q.pop();
return tmp;
}

int top() {
return q.back();
}

bool empty() {
return q.empty();
}
private:
queue<int> q;
};

单调队列

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
//最大值总是在队首
class MonotonicQueue
{
public:
MonotonicQueue();
void push(int val);
void pop(int val);
int getmax(){return q.front();}
private:
deque<int> q;
};
MonotonicQueue::MonotonicQueue() : q()
{}
void MonotonicQueue::push(int val)
{
while(!q.empty() && q.back()<val) q.pop_back();
q.push_back(val);
}
void MonotonicQueue::pop(int val)
{
if(!q.empty() && val==q.front()) q.pop_front();
}

滑动窗口最大值

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution {
public:
vector<int> maxSlidingWindow(vector<int>& nums, int k) {
vector<int> ans;
MonotonicQueue sq;
for(int i=0;i<k;++i) sq.push(nums[i]);
ans.push_back(sq.getmax());
for(vector<int>::size_type j=k;j<nums.size();++j){
sq.pop(nums[j-k]);
sq.push(nums[j]);
ans.push_back(sq.getmax());
}
return ans;
}
};