lc_b_栈和队列设计(都需要不断踢出非法元素的过程)
c. 用栈实现队列
class MyQueue {
public:
stack<int> a,b;
MyQueue() {
}
void push(int x) {
while (!a.empty()) b.push(a.top()), a.pop();
a.push(x);
while (!b.empty()) a.push(b.top()), b.pop();
}
int pop() {
if (a.empty()) return -1;
int ans = a.top(); a.pop();
return ans;
}
int peek() {
return a.empty() ? -1 : a.top();
}
bool empty() {
return a.empty();
}
};
c. 用队列实现栈
class MyStack {
public:
queue<int> a,b;
MyStack() {
}
void push(int x) {
a.push(x);
}
int pop() {
if (a.empty()) return -1;
while (a.size() > 1) {
b.push(a.front()); a.pop();
}
int ans = a.front(); a.pop();
queue<int> c = a;
a = b;
b = c;
return ans;
}
int top() {
return a.empty() ? -1 : a.back();
}
bool empty() {
return a.empty();
}
};
b. 队列的最大值
要求函数max_value、push_back 和 pop_front 的均摊时间复杂度都是O(1)。
type MaxQueue struct {
q []int
t []int
}
func Constructor() MaxQueue {
return MaxQueue {
make([]int,0),
make([]int,0),
}
}
func (MQ *MaxQueue) Max_value() int {
if (len(MQ.q) == 0) {
return -1
}
return MQ.t[0]
}
func (MQ *MaxQueue) Push_back(v int) {
for (len(MQ.t) > 0 && v > MQ.t[len(MQ.t)-1]) { //如果v是最大,为了O(1)拿到最大,我应该踢掉t队尾比v小的值
MQ.t = MQ.t[:len(MQ.t)-1]
}
MQ.t, MQ.q = append(MQ.t, v), append(MQ.q, v)
}
func (MQ *MaxQueue) Pop_front() int {
if (len(MQ.q) == 0) {
return -1
}
v := MQ.q[0]
MQ.q = MQ.q[1:]
if (len(MQ.t) > 0 && v == MQ.t[0]) {
MQ.t = MQ.t[1:]
}
return v
}
b. 设计循环队列
终点是 rear 函数
type MyCircularQueue struct {
q []int
l, r, cap int
}
func Constructor(k int) MyCircularQueue {
return MyCircularQueue{
q: make([]int, k+1),
l: 0,
r: 0,
cap: k+1,
}
}
func (this *MyCircularQueue) EnQueue(value int) bool {
if (this.IsFull()) {
return false
}
this.q[this.r] = value
this.r = (this.r + 1) % this.cap
return true
}
func (this *MyCircularQueue) DeQueue() bool {
if (this.IsEmpty()) {
return false
}
this.l = (this.l + 1) % this.cap
return true
}
func (this *MyCircularQueue) Front() int {
if (this.IsEmpty()) {
return -1
}
return this.q[this.l]
}
func (this *MyCircularQueue) Rear() int {
if (this.IsEmpty()) {
return -1
}
return this.q[(this.r-1+this.cap)%this.cap] //r指向最后一个元素的下一个位置,假如r=0,就是cap-1
}
func (this *MyCircularQueue) IsEmpty() bool {
return this.l == this.r
}
func (this *MyCircularQueue) IsFull() bool {
return (this.r + 1) % this.cap == this.l
}