150. 逆波兰表达式求值,想到使用堆来实现就简单很多,代码如下
#include<iostream>
#include<string>
#include<stack>
#include<vector>
using namespace std;
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();
st.pop();
int num2 = st.top();
st.pop();
if (tokens[i] == "+") st.push(num1+num2);
if (tokens[i] == "-") st.push(num1-num2);
if (tokens[i] == "*") st.push(num1*num2);
if (tokens[i] == "/") st.push(num1/num2);
}else{
st.push(stoi(tokens[i]));
}
}
return st.top();
}
int main(){
vector<string> tokens = {"2", "1", "+", "3", "*"};
cout << "Result: " << evalRPN(tokens) << endl; // 输出 9
return 0;
}
239. 滑动窗口最大值,单调队列实现
#include <deque>
#include <vector>
#include <iostream>
using namespace std;
vector<int> maxSlidingWindow (vector<int> nums,int n){
vector<int> max_values;
deque<int> deq;
for(int i = 0;i < nums.size(); i++){
if (!deq.empty() && deq.front() == i - n)// 去掉滑动窗口索引外的值
{
deq.pop_front();
}
while (!deq.empty() && nums[i] > nums[deq.back()])// 当新加入值大于队列尾部时把尾部去掉
{
deq.pop_back();
}
deq.push_back(i);//加入队列,无论什么条件都要执行 这个不放条件判断里面
if (i > n - 1)//达到窗口值的时候开始记录结果
{
max_values.push_back(deq.front());
}
}
return max_values;
}
int main(){
std::vector<int> nums = {1, 3, -1, -3, 5, 3, 6, 7};
int k = 3;
std::vector<int> result = maxSlidingWindow(nums, k);
std::cout << "Max values in each sliding window: ";
for (int num : result) {
std::cout << nums[num] << " ";//注意保存的是索引
}
std::cout << std::endl;
return 0;
}
347.前 K 个高频元素,使用最小堆来实现,考察优先级队列的使用,有点难。
#include <vector>
#include <unordered_map>
#include <queue>
#include <iostream>
using namespace std;
std::vector<int> topKFrequent(std::vector<int>& nums, int k) {
// 哈希表统计频率
unordered_map<int,int> frequencyMap;
for(int num:nums){
frequencyMap[num]++;
}
auto comp = [&](int left,int right){
return frequencyMap[left] > frequencyMap[right];
};
priority_queue<int,vector<int>,decltype(comp)> minHeap(comp);
for(auto &[num,freq]:frequencyMap){
minHeap.push(num);
if(minHeap.size() > k){
minHeap.pop();
}
}
std::vector<int> topK;
while (!minHeap.empty()) {
topK.push_back(minHeap.top());
minHeap.pop();
}
return topK;
}
int main() {
std::vector<int> nums = {1, 1, 1, 2, 2, 3};
int k = 2;
std::vector<int> result = topKFrequent(nums, k);
std::cout << "Top " << k << " frequent elements: ";
for (int num : result) {
std::cout << num << " ";
}
std::cout << std::endl;
return 0;
}