目录
[150. 逆波兰表达式求值](#150. 逆波兰表达式求值)
[239. 滑动窗口最大值](#239. 滑动窗口最大值)
[347. 前 K 个高频元素](#347. 前 K 个高频元素)
150. 逆波兰表达式求值
string转int方法:stk.push(stoi(t));
cpp
class Solution {
public:
int evalRPN(vector<string>& tokens) {
stack<int> stk;
for (string& t : tokens) {
if(t=="+"||t=="-"||t=="*"||t=="/") {
int b = stk.top();stk.pop();
int a = stk.top();stk.pop();
if (t == "+") stk.push(a + b);
else if (t == "-")stk.push(a-b);
else if(t=="*")stk.push(a*b);
else stk.push(a/b);
}
else stk.push(stoi(t));
}
return stk.top();
}
};
239. 滑动窗口最大值
优先队列
cpp
class Solution {
public:
vector<int> maxSlidingWindow(vector<int>& nums, int k) {
priority_queue<pair<int,int>> q;
vector<int> ans;
for(int i=0;i<k;i++){
q.emplace(nums[i],i);
}
ans.push_back(q.top().first);
for(int i=k;i<nums.size();i++){
q.emplace(nums[i],i);
while(q.top().second<=i-k){
q.pop();
}
ans.push_back(q.top().first);
}
return ans;
}
};
单调队列(双端队列)
cpp
class Solution {
public:
vector<int> maxSlidingWindow(vector<int>& nums, int k) {
deque<int> q;
vector<int> ans;
for (int i = 0; i < k; i++) {
while (!q.empty() && nums[i] >= nums[q.back()]) {
q.pop_back();
}
q.push_back(i);
}
ans.push_back(nums[q.front()]);
for (int i = k; i < nums.size(); i++) {
while (!q.empty() && nums[i] >= nums[q.back()]) {
q.pop_back();
}
q.push_back(i);
while (q.front() <= i - k) {
q.pop_front();
}
ans.push_back(nums[q.front()]);
}
return ans;
}
};
347. 前 K 个高频元素
哈希表
cpp
class Solution {
static bool com(pair<int, int>& a, pair<int, int>& b) {
return a.second > b.second;
}
public:
vector<int> topKFrequent(vector<int>& nums, int k) {
unordered_map<int, int> map;
for (int t : nums) {
map[t]++;
}
vector<pair<int, int>> gra;
for (auto& [key, value] : map) {
gra.push_back({key, value});
}
sort(gra.begin(), gra.end(), com);
vector<int> ans;
for (int i = 0; i < k; i++) {
ans.push_back(gra[i].first);
}
return ans;
}
};
哈希表+桶排序
cpp
class Solution {
public:
vector<int> topKFrequent(vector<int>& nums, int k) {
unordered_map<int,int> map;
for(int t:nums){
map[t]++;
}
vector<vector<int>> bucket(nums.size()+1);
vector<int> ans;
for(auto& [key,value]:map){
bucket[value].push_back(key);
}
for(int i=nums.size();i>=1&&ans.size()<k;i--){
for(int x:bucket[i]){
ans.push_back(x);
}
}
return ans;
}
};
