代码随想录算法训练营第十天|LeetCode232.用栈实现队列、LeetCode225.用队列实现栈
第九天是关于kmp的内容,这个放到以后再慢慢探究
232. 用栈实现队列
题目链接:232. 用栈实现队列
思路:
- 栈和队列对于元素进出的顺序刚好相反,所以通过栈实现队的时候就需要思考怎么实现这种相反的逻辑
- 对于一个栈来说,后进入的元素先抛出,那如果把栈里元素再插入另一个栈中
- 假设第一个栈叫栈一,第二个栈叫栈二,那么先进入栈一的元素会在栈底,转移到栈二只有就位于栈顶了
- 这样就用栈实现了先进先出
这是我的版本的代码,在每次入栈的时候,都整理得到一先插入的元素在栈顶的栈
时间复杂度:O(n)
,空间复杂度O(n)
代码:
class MyQueue
{
public:
MyQueue()
{
}
void push(int x)
{
while (!simulate_list.empty())
{
temp_s.push(simulate_list.top());
simulate_list.pop();
}
temp_s.push(x);
while (!temp_s.empty())
{
simulate_list.push(temp_s.top());
temp_s.pop();
}
}
int pop()
{
int temp = simulate_list.top();
simulate_list.pop();
return temp;
}
int peek()
{
return simulate_list.top();
}
bool empty()
{
return simulate_list.empty();
}
std::stack<int> temp_s;
std::stack<int> simulate_list;
};
总结:
- 对比carl哥的代码,在需要出栈的时候才转移栈内元素,感觉他这样的代码,移动栈的次数会更少一些,性能应该会更好
- 做题体验:
哈哈
(哈哈
>嘿嘿
>哎哎
>嘤嘤
) - 时间:
10min
一刷
225. 用队列实现栈
题目链接:225. 用队列实现栈
思路:
- 和上一道题实现的结果相反,如果惯性思维认为,还需要用两个队列,那就会有问题
- 因为队列是先进先出的结构,把一个队列转移到另一个队列的时候还是原先的顺序
- 这里我就用一个队列,插入的时候按照队列本身的方式插入
- 当要抛出队尾元素的时候,可以将队头元素依次移到队尾,让本身的队尾元素变成对头
时间复杂度:O(n)
,空间复杂度O(n)
代码:
class MyStack
{
public:
std::queue<int> simu_stack;
MyStack()
{
}
void push(int x)
{
simu_stack.push(x);
}
int pop()
{
int size = simu_stack.size();
for (int i = 0; i < size - 1; ++i)
{
simu_stack.push(simu_stack.front());
simu_stack.pop();
}
int res = simu_stack.front();
simu_stack.pop();
return res;
}
int top()
{
int res = this->pop();
simu_stack.push(res);
return res;
}
bool empty()
{
return simu_stack.empty();
}
};
总结:
- carl哥这里第一种解法用到了两个队列,其中一个是辅助队列作为备份,这和我上一题的思想其实比较接近
- 做题体验:
哈哈
(哈哈
>嘿嘿
>哎哎
>嘤嘤
) - 时间:
15min
一刷