Code Exercising Day 10 of “Code Ideas Record“:StackQueue part02

文章目錄

    • 【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…