第十一题:化栈为队
自己的思路:
→push按照栈的形式正常压入S
→pop和top利用辅助栈temp_S,把栈S中数据不断弹出压入temp_S,
→相当于逆序入栈,这个时候temp_S的栈顶就是S的栈底,
→相当于弹出的就是队列的头
class MyQueue {
private:
stack<int> S;//以栈的形式存数
stack<int> temp_S;//每次pop或top,用于倒栈
public:
/** Initialize your data structure here. */
MyQueue() {
}
/** Push element x to the back of queue. */
void push(int x) {
S.push(x);
}
/** Removes the element from in front of queue and returns that element. */
int pop() {
int res=0;
if(S.empty()==1) return -1;
//逆序入栈
while(S.empty()==0){
temp_S.push(S.top());
S.pop();
}
res=temp_S.top();
temp_S.pop();
//压回原栈
while(temp_S.empty()==0){
S.push(temp_S.top());
temp_S.pop();
}
return res;
}
/** Get the front element. */
int peek() {
int res=0;
if(S.empty()==1) return -1;
//逆序入栈
while(S.empty()==0){
temp_S.push(S.top());
S.pop();
}
res=temp_S.top();
//压回原栈
while(temp_S.empty()==0){
S.push(temp_S.top());
temp_S.pop();
}
return res;
}
/** Returns whether the queue is empty. */
bool empty() {
return S.empty()? true:false;
}
};
期间遇到bug:循环遍历栈的时候判断栈不空的时候写成temp_S.empty()!=0,造成runtime error
♥改为temp_S.empty()==0
第十二题:节点间通路
自己没有想出来,
别人的思路:建图+dfs
class Solution {
public:
vector<unordered_set<int>> edge;//存图,记录每一条边的邻接边(有向的)
unordered_set<int> visited;
bool dfs(int cur, int target) {
if(visited.count(cur)) return false;
visited.insert(cur);//记录访问过的节点
if(cur == target) return true;//递归结束条件,当前节点为终点
for(auto v : edge[cur]) {
if(dfs(v, target))//在这边如果遇到false,继续探寻下一条边
return true;
}
return false;
}
bool findWhetherExistsPath(int n, vector<vector<int>>& graph, int start, int target) {
edge.resize(n);//调整容器的大小,使其包含n个元素
for(auto &e : graph)//依次取出graph元素
edge[e[0]].insert(e[1]);//构建图
return dfs(start, target);
}
};
auto关键字
https://www.cnblogs.com/Nothing-9708071624/p/10167982.html
https://zhuanlan.zhihu.com/p/348520921