前言
一个本硕双非的小菜鸡,备战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]入栈。
- 如果当前要出栈的popV[i]元素在栈首,那么我们将其弹出。
- 如果当前要出栈的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;
}
};
总结
祝大家都能学有所成,找到一份好工作!