Day4:题库
一:用栈模仿队列
2个栈,一个栈用来入,一个栈用来出
class CQueue {
public:
stack<int >A,B;
CQueue() {} //构造函数
void appendTail(int value) {
A.push(value); //入的都在这里,虽然待会去B删,但是这里是仓库,等B删完再回来拿
}
int deleteHead() {
if(A.empty()&&B.empty())
return -1;
if(!B.empty()){ //弹出首元素
int temp = B.top();
B.pop();
return temp;
}
while(!A.empty()) //假如开局 B空
{
int temp = A.top();
A.pop();
B.push(temp);
}
int temp = B.top();
B.pop();
return temp;
}
};
/**
* Your CQueue object will be instantiated and called as such:
* CQueue* obj = new CQueue();
* obj->appendTail(value);
* int param_2 = obj->deleteHead();
*/
二:用队列模仿栈
先考虑push!!!
stl: queue<int >q;
q.front()
class MyStack {
public:
queue<int> q;
/** Initialize your data structure here. */
MyStack() {
}
/** Push element x onto stack. */
void push(int x) { //每次注入,都调整一次顺序!!!!
int n = q.size();
q.push(x);
for (int i = 0; i < n; i++) {
q.push(q.front());
q.pop();
}
}
/** Removes the element on top of the stack and returns that element. */
int pop() { //在阶段一 的基础上 pop top
int r = q.front();
q.pop();
return r;
}
/** Get the top element. */
int top() {
int r = q.front();
return r;
}
/** Returns whether the stack is empty. */
bool empty() {
return q.empty();
}
};
Day5:两道题 + 一道面试变形题
- 剑指 Offer 30. 包含min函数的栈
- 变形题:最小栈的最优解(本问题卡打卡区)
offer 30:栈 带有 min函数
辅助 一个栈,用来存放最小min。在push上,和pop上注意!
要考虑好边界条件:B是否为空!
语法细节:让empty在前。
class MinStack {
public:
/** initialize your data structure here. */
stack<int>A,B;
MinStack() {
}
void push(int x) { //压入:先考虑B空,再Btop(防止极端情况)
A.push(x);
if(B.empty()||x<=B.top())
B.push(x);
}
void pop() { //看看是否B中也要pop()
int temp = A.top();
if(temp==B.top())
B.pop();
A.pop();
}
int top() {
return A.top();
}
int getMin() {
return B.top();
}
};
剑指Offer 31. 栈的压入、弹出序列
栈的压入弹出序列合法性判断
输入:两个vector 输入 ,输出序列
辅助数据结构:stack
神奇问题:top 换成 num不行了
class Solution {
public:
bool validateBookSequences(vector<int>& putIn, vector<int>& takeOut) {
stack<int> stk; //1. 辅助栈
int i = 0;
for(int num : putIn) { //2. 利用putIn vector 序列
stk.push(num); // num 入栈
while(!stk.empty() && stk.top() == takeOut[i]) { // 3. 循环判断与出栈 takeOut 序列
stk.pop();
i++;
}
}
return stk.empty();
}
};
public class 设计一个有gitMin的栈 {
private Stack<Integer> stack = new Stack<Integer>();
private int min;
public void push(int x) {
if (stack.isEmpty()) {
min = x;
stack.push(0);
} else {
// 计算差值
int compare = x - min;
stack.push(compare);
// 如果差值小于0,显然 x 成为最小值,否则最小值不变
min = compare < 0 ? x : min;
}
}
public void pop() {
int top = stack.peek();
// 如果top小于0,显然最小值也一并会被删除,此时更新最小值
min = top < 0 ? (min - top) : min;
stack.pop();
}
public int getMin() {
return min;
}
}