文章目录

    • 【150. Evaluate Reverse Polish Notation】
    • 【239. Sliding Window Maximum】
    • 【347. Top K Frequent Elements】

【150. Evaluate Reverse Polish Notation】

Problem Link
Approach: Use a stack. Push numbers onto the stack; when encountering an operator, pop the top two numbers, perform the operation, and push the result back onto the stack.
Helper Function: stoll function: converts a string to a long long type.

class Solution {
public:int evalRPN(vector<string>& tokens) {// LeetCode has modified the backend test data, so long long is neededstack<long long> st; for (int i = 0; i < tokens.size(); i++) {if (tokens[i] == "+" || tokens[i] == "-" || tokens[i] == "*" || tokens[i] == "/") {long long num1 = st.top();st.pop();long long num2 = st.top();st.pop();if (tokens[i] == "+") st.push(num2 + num1);if (tokens[i] == "-") st.push(num2 - num1);if (tokens[i] == "*") st.push(num2 * num1);if (tokens[i] == "/") st.push(num2 / num1);} else {st.push(stoll(tokens[i]));}}long long result = st.top();st.pop(); // Pop the last element from the stack (though it's not strictly necessary)return result;}
};

【239. Sliding Window Maximum】

Problem Link
Approach: In fact, the queue doesn’t need to maintain all elements within the window. It only needs to maintain elements that could potentially become the maximum in the window, while ensuring the elements in the queue are ordered from largest to smallest.

This type of queue that maintains elements in monotonically decreasing order is called a monotonic queue, i.e., a queue that is either monotonically decreasing or increasing. C++ does not directly support monotonic queues, so we need to implement one ourselves.

Do not assume that implementing a monotonic queue means sorting the numbers within the window. If sorting were involved, how would it differ from a priority queue?

When designing the monotonic queue, the pop and push operations must adhere to the following rules:

  1. pop(value): If the element being removed from the window (value) equals the exit element of the monotonic queue, then the queue pops this element. Otherwise, no action is taken.
  2. push(value): If the element being pushed (value) is greater than the value of the entry element in the queue, then the entry elements of the queue are popped until the value being pushed is less than or equal to the value of the entry element.
    By adhering to these rules, whenever the window moves, you can simply query que.front() to return the current maximum value in the window.

Using a deque to implement this monotonic queue is most appropriate.
Solution Demo

class Solution {
private:class MyQueue { // Monotonic Queue (decreasing order)public:deque<int> que; // Using deque to implement the monotonic queue// When popping, check if the current value to pop equals the front element of the queue.// Also, check if the queue is currently empty before popping.void pop(int value) {if (!que.empty() && value == que.front()) {que.pop_front();}}// If the value being pushed is greater than the back element of the queue,// pop elements from the back until the pushed value is less than or equal to the back element.// This ensures the queue remains in decreasing order.void push(int value) {while (!que.empty() && value > que.back()) {que.pop_back();}que.push_back(value);}// Query the current maximum in the queue by simply returning the front element.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++) { // First, push the first k elements into the queueque.push(nums[i]);}result.push_back(que.front()); // Record the maximum of the first k elementsfor (int i = k; i < nums.size(); i++) {que.pop(nums[i - k]); // Remove the leftmost element of the sliding windowque.push(nums[i]); // Add the new rightmost element to the sliding windowresult.push_back(que.front()); // Record the corresponding maximum}return result;}
};

【347. Top K Frequent Elements】

Problem Link
Approach: Use a min-heap implemented with a priority queue to sort frequencies (the min-heap is used to exclude the smallest frequencies while maintaining the top K frequencies).
Key Code:

class mycomparison {
public:bool operator()(const pair<int, int>& lhs, const pair<int, int>& rhs) {return lhs.second > rhs.second;// '>' creates a min-heap, opposite to quicksort  }
};priority_queue<pair<int, int>, vector<pair<int, int>>, mycomparison> pri_que;for (unordered_map<int, int>::iterator it = map.begin(); it != map.end(); it++) {pri_que.push(*it);if (pri_que.size() > k) { // If the heap size exceeds K, pop the smallest to maintain size K  pri_que.pop();}
}
class Solution {
public:// Min-heap  class mycomparison {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) {// Count element frequencies  unordered_map<int, int> map; // map<nums[i], frequency>  for (int i = 0; i < nums.size(); i++) {map[nums[i]]++;}// Sort frequencies  // Define a min-heap of size k  priority_queue<pair<int, int>, vector<pair<int, int>>, mycomparison> pri_que;// Traverse all frequencies with the fixed-size min-heap  for (unordered_map<int, int>::iterator it = map.begin(); it != map.end(); it++) {pri_que.push(*it);if (pri_que.size() > k) { // If the heap size exceeds K, pop the smallest to maintain size K  pri_que.pop();}}// Extract the top K frequent elements  // Since the min-heap pops the smallest first, reverse the output order  vector<int> result(k);for (int i = k - 1; i >= 0; i--) {result[i] = pri_que.top().first;pri_que.pop();}return result;}
};

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如若转载,请注明出处:http://www.pswp.cn/web/92632.shtml
繁体地址,请注明出处:http://hk.pswp.cn/web/92632.shtml
英文地址,请注明出处:http://en.pswp.cn/web/92632.shtml

如若内容造成侵权/违法违规/事实不符,请联系英文站点网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

系统架构设计师备考之架构设计高级知识

1.系统架构设计基础知识1.1.软件架构概念软件架构定义软件架构&#xff08;Software Architecture&#xff09;或称软件体系结构&#xff0c;是指系统的一个或者多个结构&#xff0c;这些结构包括软件的构件&#xff08;可能是程序模块、类或者是中间件&#xff09;、构件的外部…

PWM波的频谱分析及matlab 验证[电路原理]

你知道吗&#xff1f;pwm可以制作adc模块哦&#xff01;这样普通的gpio也能实现adc功能了。 我们嵌入式日常接触的pwm波&#xff0c;你真的了解他吗&#xff1f; 只有知道PWM的频谱是怎么样的&#xff0c;才能设计合适的滤波器&#xff0c;下面我们一起从底层数学原理来推导PWM…

相机、镜头参数详解以及相关计算公式

一、工业相机参数 1、分辨率 相机每次采集图像的像素点数&#xff0c;也是指这个相机总共有多少个感光晶片。在采集图像时&#xff0c;相机的分辨率对检测精度有很大的影响&#xff0c;在对同样大的视场成像时&#xff0c;分辨率越高&#xff0c;对细节的展示越明显。 相机像素…

通信中间件 Fast DDS(一) :编译、安装和测试

目录 1.简介 2.Windows编译、安装和测试 2.1.编译环境准备 2.2.编译安装 2.2.1.安装FastCDR 2.2.2.安装Foonathan Memory 2.2.3.安装FastDDS 2.3.验证安装 3.Linux编译、安装和测试 3.1.编译环境准备 3.2.编译安装 3.2.1.安装FastCDR 3.2.2.安装Foonathan M…

NI USRP X410 无线电上的雷达目标仿真

此示例展示如何在 NI™ USRP™ 无线电的 FPGA 上部署雷达目标仿真算法。 介绍 在本例中&#xff0c;您将从 Simulink 模型入手&#xff0c;该模型可模拟最多四个雷达目标响应。您将按照分步指南&#xff0c;在 Simulink 中从该模型生成比特流&#xff0c;并使用生成的 MATLAB 主…

PyTorch 深度学习实战教程-番外篇04:卷积层详解与实战指南

标签&#xff1a;# 深度学习 #人工智能 #神经网络 #PyTorch #卷积神经网络 相关文章&#xff1a; 《Pytorch深度学习框架实战教程01》 《Pytorch深度学习框架实战教程02&#xff1a;开发环境部署》 《Pytorch深度学习框架实战教程03&#xff1a;Tensor 的创建、属性、操作与…

LeetCode 面试经典 150_数组/字符串_分发糖果(15_135_C++_困难)(贪心算法)

LeetCode 面试经典 150_数组/字符串_分发糖果&#xff08;15_135_C_困难&#xff09;题目描述&#xff1a;输入输出样例&#xff1a;题解&#xff1a;解题思路&#xff1a;思路一&#xff08;贪心算法&#xff09;&#xff1a;代码实现代码实现&#xff08;思路一&#xff08;贪…

配置timer控制 IO的输出(STC8)

使用STC8的Timer控制IO输出 STC8系列单片机具有多个定时器&#xff0c;可以用于精确控制IO口的输出状态。以下是使用Timer0和Timer1控制IO输出的方法。 初始化Timer0 配置Timer0为16位自动重装模式&#xff0c;用于周期性控制IO输出&#xff1a; /************************ 定时…

【Python练习】086. 编写一个函数,实现简单的DHCP服务器功能

086. 编写一个函数,实现简单的DHCP服务器功能 086. 编写一个函数,实现简单的DHCP服务器功能 安装依赖库 示例代码 代码说明 示例输出 注意事项 扩展功能 DHCP服务器功能实现方法 依赖库安装 基本功能实现 功能说明 运行方法 注意事项 扩展功能 086. 编写一个函数,实现简单的…

生产环境Tomcat运行一段时间后,如何测试其性能是否满足后续使用

要测试生产环境中已运行一段时间的Tomcat性能是否满足后续使用需求&#xff0c;需从基础监控、负载压力测试、配置合理性校验、稳定性验证等多维度入手&#xff0c;结合工具和实际业务场景定位瓶颈&#xff0c;确保其能应对未来可能的流量增长。以下是具体方法和步骤&#xff1…

Qt中的设计模式:经典的MVC,MVP和MVVM

Qt中的设计模式&#xff1a;经典的MVC&#xff0c;MVP和MVVM 前言 ​ 笔者这里最近正在研究经典的三大 Model/View 框架&#xff0c;不得不说&#xff0c;我先前的确写过Qt在这里的体现&#xff0c;但是&#xff0c;笔者认为之前的文章中&#xff0c;我只是机械的memcpy的Qt的…

Windows浮动ip怎么配置

Windows浮动IP怎么配置&#xff0c;达到IP漂移的效果&#xff0c;方法肯定是有的&#xff0c;这里我推荐一款好用的高可用Vip漂移软件PanguVip&#xff0c;我们先看下最终达到的效果图&#xff0c;如下所示PanguVip软件免费下载百度网盘为您提供文件的网络备份、同步和分享服务…

[langchain] Sync streaming vs Async Streaming

我不太清楚langchain中的sync stream 和 async steam有什么关系和区别sync stream from langchain.chat_models import init_chat_model from langchain_deepseek.chat_models import ChatDeepSeek import dotenv dotenv.load_dotenv()messages [ ("system", &quo…

nginx下lua的实现机制、Lua错误处理、面向对象

nginx下lua的实现机制 nginxlua概述 nginx&#xff1a;功能由模块提供。 http模块、events模块&#xff0c;mail模块。 处理http请求的时候&#xff0c;可以利用模块做一些功能&#xff1a;eg&#xff1a;登录校验&#xff0c;js合并&#xff0c;数据库访问&#xff0c;鉴权。 …

Axure基于中继器实现的组件库(导航菜单、动态表格)

摘要 本文将为您详细介绍基于 Axure 的中继器组件库中的 9 个独特组件&#xff0c;这些组件不仅能够极大地提升您的原型设计效率&#xff0c;还能为您的项目增添令人惊叹的交互效果和视觉呈现。 引言 在当今快速发展的数字产品设计领域&#xff0c;原型设计工具的革新不断推动着…

Kafka 生产者与消费者分区策略全解析:从原理到实践

一、生产者分区策略1.1 分区好处&#xff08;1&#xff09;便于合理使用存储资源&#xff0c;每个Partition在一个Broker上存储&#xff0c;可以把海量的数据按照分区切割成一块一块数据存储在多台Broker上。合理控制分区的任务&#xff0c;可以实现负载均衡的效果。&#xff0…

高频面试点:深入理解 TCP 三次握手与四次挥手

在网络通信的世界里,TCP(Transmission Control Protocol,传输控制协议)是确保数据可靠传输的基石。其中,三次握手建立连接、四次挥手断开连接的过程,更是 Java 秋招面试中的高频考点。今天,我们就深入剖析这两个关键过程,结合原理、代码示例与面试真题,帮你吃透知识点…

k8s-nfs实现创建sc的两种方式

法一&#xff1a;基于 官方 NFS CSI 插件 法二&#xff1a;基于 nfs-subdir-external-provisioner 法一 官方 NFS CSI 插件 大致步骤# 安装 NFS sudo apt update sudo apt install -y nfs-kernel-server # 创建共享目录 sudo mkdir -p /data/nfs sudo chmod 777 /data/nfs # 配…

n8n 入门指南:更适合跨境出海搞钱的AI智能体

如果你最近刷到 AI 圈的分享应该会发现——n8n 又火起来了。其实 n8n 早在 2020 年左右就被程序员玩过一波&#xff0c;当时很多人拿它做网站自动发邮件、消息转发之类的“流程自动化”。但那时候 AI 还没这么卷&#xff0c;大家也没觉得多有用。n8n为什么最近又翻红&#xff1…

【数据分享】各省农业土地流转率(2010-2023)

数据介绍土地流转是推动农业规模化、现代化发展的关键机制。为助力相关研究&#xff0c;现分享一份覆盖全国30个省级行政区、时间跨度为2010-2023年的农业土地流转率面板数据集。本数据直接提取自权威统计年报&#xff0c;具有较高的参考价值。一、数据概览覆盖范围&#xff1a…