150. 逆波兰表达式求值
思路:遇到符号弹出上两个元素,注意要将string转成int。
题解:
class Solution {
public:
int evalRPN(vector<string>& tokens) {
stack<int> res;
for (string ch : tokens)
{
if (ch == "+" || ch == "-" || ch == "*" || ch == "/")
{
int num2 = res.top();
res.pop();
int num1 = res.top();
res.pop();
if (ch == "+") res.push(num1 + num2);
else if (ch == "-") res.push(num1 - num2);
else if (ch == "*") res.push(num1 * num2);
else res.push(num1 / num2);
}
else
res.push(stoi(ch));
}
return res.top();
}
};
239. 滑动窗口最大值
思路:单调队列,队列内元素从小到大,只需要维护窗口中的最大值及右侧的部分元素,最大值左侧的元素无用。
题解:
class Solution {
private:
class Myque
{
private:
deque<int> que;
public:
void pop(int val)
{
if (!que.empty() && que.front() == val)
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) {
Myque 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.前 K 个高频元素
思路:考察priority_queue,默认大顶堆。由于比较的是结构体优先级,我们需要自定义全局比较规则,构建出根据出现次数排序的小顶堆。
题解:
class Solution {
public:
class cmp{
public:
bool operator()(const pair<int, int> &p1, const pair<int, int> &p2){
return p1.second > p2.second;
}
};
vector<int> topKFrequent(vector<int>& nums, int k) {
unordered_map<int, int> map;
for (int num : nums)
++map[num];
priority_queue<pair<int, int>, vector<pair<int,int>>, cmp> q;
for (auto it : map)
{
q.push(it);
if (q.size() > k)
q.pop();
}
vector<int> res;
for (int i = 0; i < k; ++i)
{
res.push_back(q.top().first);
q.pop();
}
return res;
}
};