150. 逆波兰表达式求值
class Solution {
public:
int evalRPN(vector<string>& tokens) { // 字符串数组
stack<int> st;
for (int i = 0; i < tokens.size(); i++) {
if (tokens[i] == "+" || tokens[i] == "-" || tokens[i] == "*" ||
tokens[i] == "/") {
int num1 = st.top(); //long long8字节 64位 从int4字节32位[−2^31, 2^31−1]升级到[−2^63,2^63−1]
st.pop();
int num2 = st.top();
st.pop();
if (tokens[i] == "+") {
st.push(num2 + num1);
} else if (tokens[i] == "-") {
st.push(num2 - num1);
} else if (tokens[i] == "*") {
st.push(num2 * num1);
} else if (tokens[i] == "/") {
st.push(num2 / num1);
}
} else {
st.push(stoi(tokens[i])); // 因为栈为int类型 stoi stoll 将字符串转换为整数,然后推入栈中
}
}
return st.top();
}
};
239. 滑动窗口最大值
push_back:这是针对顺序容器(如
std::vector、std::deque、std::list)的成员函数。它用于将元素添加到容器的末尾位置。push:这是针对适配器容器(如
std::stack和std::queue)的成员函数。对于堆栈容器,push将元素推入堆栈的顶部;对于队列容器,push将元素添加到队列的末尾。
class Solution {
private:
class MyQueue { // 实现单调队列
public:
deque<int> que; // double end queue双端队列
void pop(int val) {
if (!que.empty() && val == que.front()) {
que.pop_front();
}
}
void push(int val) {
while (!que.empty() && val > que.back()) {
que.pop_back();
}
que.push_back(val);
}
int front() { return que.front(); }
};
public:
vector<int> maxSlidingWindow(vector<int>& nums, int k) {
MyQueue que;
vector<int> result;
for (int i = 0; i < k; i++) {
que.push(nums[i]);
}
result.push_back(que.front());
// std::vector 是 C++ 标准库中的一个动态数组容器,它提供了push_back成员函数来在容器的末尾添加一个新元素
for (int i = k; i < nums.size(); i++) {
que.pop(nums[i - k]);
que.push(nums[i]);
result.push_back(que.front());
}
return result;
}
};
347.前 K 个高频元素
priority_queue<Type, Container, Functional>;Type是要存放的数据类型
Container是实现底层堆的容器,必须是数组实现的容器,如vector、deque
Functional是比较方式/比较函数/优先级
class Solution {
public:
vector<int> topKFrequent(vector<int>& nums, int k) {
unordered_map<int,int>map;
for(int i=0;i<nums.size();i++){
map[nums[i]]++;
}
//自定义优先队列的比较方式-小顶堆
struct myComparison{
bool operator()(pair<int,int>&p1,pair<int,int>&p2){
return p1.second>p2.second;
}
};
//创建优先队列
priority_queue<pair<int,int>,vector<pair<int,int>>,myComparison>que;
//遍历map
for(auto& a:map){
que.push(a);
if(que.size()>k){
que.pop();
}
}
vector<int> result(k);
for (int i = k - 1; i >= 0; i--) {
result[i] = que.top().first;
que.pop();
}
return result;
}
};
320

被折叠的 条评论
为什么被折叠?



