程序员面试金典03-刷题回忆录
03.01 三合一
基本看不懂题,直接看别人代码倒是很清晰。。。
class TripleInOne {
private:
//这里是我们的私有数据,我们设置一个vector来存储数据
//然后用一个数组来存储这个我们三个栈的指针的位置可以这么说
vector<int> s;
int stackSize;
int spointer[3];
public:
//这里进行初始化;
TripleInOne(int stackSize) {
s = vector<int>(stackSize*3, 0);
this->stackSize = stackSize;
spointer[0] = 0;
spointer[1] = stackSize;
spointer[2] = stackSize*2;
}
//然后将元素push进去的话我们首先看有没有溢出的
void push(int stackNum, int value) {
if(spointer[stackNum] < (stackNum+1)*stackSize){
s[spointer[stackNum]++] = value;
}
}
//这里的pop的话就看是否有元素让你pop出来,没有的话就返回-1
int pop(int stackNum) {
int res = -1;
if(spointer[stackNum] > (stackNum)*stackSize){
res = s[--spointer[stackNum]];
}
return res;
}
//peek的操作和上面的pop操作类似,不同的点就是我们不需要把指针往后退一步
int peek(int stackNum) {
int res = -1;
if(spointer[stackNum] > (stackNum)*stackSize){
res = s[spointer[stackNum]-1];
}
return res;
}
//看看是不是空的话我们就看每个栈的指针是不是在原来的初始位置上
bool isEmpty(int stackNum) {
return spointer[stackNum] == stackNum*stackSize;
}
};
/**
* Your TripleInOne object will be instantiated and called as such:
* TripleInOne* obj = new TripleInOne(stackSize);
* obj->push(stackNum,value);
* int param_2 = obj->pop(stackNum);
* int param_3 = obj->peek(stackNum);
* bool param_4 = obj->isEmpty(stackNum);
*/
作者:wo-shi-shui-jue-wang
链接:https://leetcode-cn.com/problems/three-in-one-lcci/solution/c-jian-dan-ming-liao-yi-kan-jiu-hui-by-wo-shi-shui/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
03.02 栈的最小值
用两个栈,一个栈每次+数据,一个栈+当前的最小值。弹出的时候一起弹出。
代码略。
03.03 堆盘子
读题即可
03.04 化栈成队
两个栈来实现一个队列。(记得以前是面试重点)
代码如下(示例):
class MyQueue {
public:
/** Initialize your data structure here. */
stack<int>s1,s2; //s1存数据,s2取数据
MyQueue() {
}
/** Push element x to the back of queue. */
void push(int x) {
while(!s2.empty()){
s1.push(s2.top());
s2.pop();
}
s1.push(x);
}
/** Removes the element from in front of queue and returns that element. */
int pop() {
while(!s1.empty()){
s2.push(s1.top());
s1.pop();
}
int res = s2.top();
s2.pop();
return res;
}
/** Get the front element. */
int peek() {
while(!s1.empty()){
s2.push(s1.top());
s1.pop();
}
return s2.top();
}
/** Returns whether the queue is empty. */
bool empty() {
if(s1.empty() && s2.empty()) return true;
return false;
}
};
/**
* Your MyQueue object will be instantiated and called as such:
* MyQueue* obj = new MyQueue();
* obj->push(x);
* int param_2 = obj->pop();
* int param_3 = obj->peek();
* bool param_4 = obj->empty();
*/
03.05 栈排序(进阶算法很不错!!)
两个栈,真正利用起来
https://leetcode-cn.com/problems/sort-of-stacks-lcci/solution/cliang-chong-fu-zhu-zhan-jie-fa-by-yizhe-shi/
03.06 动物收容所
两个队列,queue<pair<int,int>> a;
貌似比较的话默认比较第一个int,所以没有重载运算符。
https://leetcode-cn.com/problems/animal-shelter-lcci/solution/cjian-ji-dai-ma-by-orangeman-r5zp/
总结
03章主要是栈与队列,尤其是用到了两个栈。
整体代码简单。
本文介绍了程序员面试中常见的栈和队列题目,包括三合一栈、栈的最小值、汉诺塔、栈队列实现、栈排序以及动物收容所问题。通过实例代码解析,展示了如何利用两个栈实现队列以及高效地解决各种问题。
1662

被折叠的 条评论
为什么被折叠?



