HOT100与剑指Offer


前言

一个本硕双非的小菜鸡,备战24年秋招,计划刷完hot100和剑指Offer的刷题计划,加油!
根据要求,每一道题都要写出两种以上的解题技巧。

一、1. 两数之和(HOT100)

1. 两数之和
Note:哈希表解题

class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        unordered_map<int, int>map;
        for (int i = 0; i < nums.size(); i++) {
            auto inet = map.find(target - nums[i]);
            if (inet != map.end())
                return {inet->second, i};
            else
                map.insert(pair<int, int>(nums[i], i));
        }
        return {};
    }
};

Note:暴力解题

class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        int n = nums.size();
        for (int i = 0; i < n; ++i) {
            for (int j = i + 1; j < n; ++j) {
                if (nums[i] + nums[j] == target) {
                    return {i, j};
                }
            }
        }
        return {};
    }
};

二、31. 栈的压入、弹出序列(剑指Offer)

栈的压入、弹出序列

Note:使用栈作为辅助,然后模拟这个过程。

假设我们已经处理了出栈序列中的前i-1个数,现在要让popV[i]出栈。如果popV[i]不在栈中,我们就要将入栈序列pushV[i]中的若干个数压进栈中,直到popV[i]入栈。

  1. 如果当前要出栈的popV[i]元素在栈首,那么我们将其弹出。
  2. 如果当前要出栈的popV[i]元素不在栈首,那么原问题无解。

最后判断st是否为空,为空则表示当前出栈序列可取。

class Solution {
public:
    bool isPopOrder(vector<int> pushV,vector<int> popV) {
        if (pushV.size() != popV.size()) return false;
        
        stack<int> st;
        
        int k = 0;
        for (int i = 0; i < popV.size(); i++) {
            while (st.empty() || popV[i] != st.top())
                st.push(pushV[k++]);
            if (st.top() == popV[i])
                st.pop();
            else
                return false;
        }
        return st.empty();
    }
};

Note:双指针解法。原理一致,但是用双指针模拟入栈出栈过程

class Solution {
public:
    bool isPopOrder(vector<int> pushV,vector<int> popV) {
        if (pushV.size() != popV.size()) return false;
        int i = 0, j = 0;
        int len = pushV.size();
        while (i < len && j < len) {
            while (i < len && pushV[i] != popV[j])
                ++i; // 模拟入栈
            if (i < len && pushV[i] == popV[j]) {
                pushV[i] = -1;
                ++j;
                while (i > 0 && pushV[i] == -1)
                    --i; // 模拟出栈
            }
        }
        return j == len ? true : false;
    }
};

总结

祝大家都能学有所成,找到一份好工作!

  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

努力找工作的小菜鸡

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值