代码随想录算法训练营第十一天 | 150. 逆波兰表达式求值, 239. 滑动窗口最大值 & 347.前 K 个高频元素
150. Evaluate Reverse Polish Notation
这道题还算简单,感觉现在对于Stack相关的题目已经能够建立起信心了!
题目链接:150. Evaluate Reverse Polish Notation
题目链接/文章讲解/视频讲解:代码随想录讲解
我的代码:
Python:
class Solution:
def evalRPN(self, tokens: List[str]) -> int:
stack = []
for t in tokens:
if t == '+':
second = stack.pop()
first = stack.pop()
stack.append(second + first)
elif t == '-':
second = stack.pop()
first = stack.pop()
stack.append(first - second)
elif t == '*':
second = stack.pop()
first = stack.pop()
stack.append(first * second)
elif t == '/':
second = stack.pop()
first = stack.pop()
stack.append(int(first / second))
else:
stack.append(int(t))
return stack.pop()
C++:
class Solution {
public:
int evalRPN(vector<string>& tokens) {
std::stack<long long> st;
for (std::string t : tokens) {
if (t == "+" || t == "-" || t == "*" || t == "/") {
long long second = st.top(); st.pop();
long long first = st.top(); st.pop();
if (t == "+") {st.push(first + second);}
if (t == "-") {st.push(first - second);}
if (t == "*") {st.push(first * second);}
if (t == "/") {st.push(first / second);}
} else {
st.push(stoll(t));
}
}
return st.top();
}
};
239. Sliding Window Maximum
这道题理解起来其实没有想象中这么难,卡哥讲的好清晰!争取二刷就能独立写出!
时间关系也只implement了C++版
题目链接:239. Sliding Window Maximum
题目链接/文章讲解/视频讲解:代码随想录讲解
我的代码:
C++:
class Solution {
private:
class MyQueue {
public:
deque<int> que;
void pop(int value) {
if (!que.empty() && value == que.front()) {
que.pop_front();
}
}
void push(int value) {
while (!que.empty() && value > que.back()) {
que.pop_back();
}
que.push_back(value);
}
int front() {
return que.front();
}
};
public:
vector<int> maxSlidingWindow(vector<int>& nums, int k) {
MyQueue que;
vector<int> res;
for (int i=0; i < k; i++) {
que.push(nums[i]);
}
res.push_back(que.front());
for (int i=k; i < nums.size(); i++) {
que.pop(nums[i-k]);
que.push(nums[i]);
res.push_back(que.front());
}
return res;
}
};
347. Top K Frequent Elements
这题让我觉得我的C++水平太烂了,还有很多很多的语法需要补全,如果用Python写应该简单一些,但因为赶进度,只implement了C++, Python版的只是看过并理解
题目链接:347. Top K Frequent Elements
题目链接/文章讲解/视频讲解:代码随想录讲解
我的代码:
C++:
class Solution {
public:
class mycomparator {
public:
bool operator()(const pair<int, int> lhs, const pair<int, int> rhs) {
return lhs.second > rhs.second;
}
};
vector<int> topKFrequent(vector<int>& nums, int k) {
unordered_map<int, int> map;
for (int n : nums) {
map[n]++;
}
priority_queue<pair<int, int>, vector<pair<int, int>>, mycomparator> pri_que;
for (unordered_map<int, int>::iterator it = map.begin(); it != map.end(); it++) {
pri_que.push(*it);
if (pri_que.size() > k) {
pri_que.pop();
}
}
vector<int> result(k);
for (int i=k-1; i >= 0; i--) {
result[i] = pri_que.top().first;
pri_que.pop();
}
return result;
}
};
总结
狂狂赶进度ing
在这儿贴一个代码随想录的栈与队列总结吧:
栈与队列总结