LeetCode刷题(2021-09-09)

这篇博客探讨了如何使用栈实现队列操作,通过辅助栈完成元素的逆序,实现了化栈为队。同时,文章介绍了利用建图和DFS解决节点间通路问题,提供了具体的C++代码实现。遇到的问题和解决方案也在文中详细说明,包括对`temp_S.empty()`的错误判断进行修正。此外,博客还提及了`auto`关键字的使用场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

第十一题:化栈为队
自己的思路:
→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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值