当前位置: 首页 > news >正文

LeetCode---栈与队列

232. 用栈实现队列

请你仅使用两个栈实现先入先出队列。队列应当支持一般队列支持的所有操作(pushpoppeekempty):

实现 MyQueue 类:

  • void push(int x) 将元素 x 推到队列的末尾
  • int pop() 从队列的开头移除并返回元素
  • int peek() 返回队列开头的元素
  • boolean empty() 如果队列为空,返回 true ;否则,返回 false

代码示例: 

class MyQueue {
public:stack<int> stIn;stack<int> stOut;/** Initialize your data structure here. */MyQueue() {}/** Push element x to the back of queue. */void push(int x) {stIn.push(x);}/** Removes the element from in front of queue and returns that element. */int pop() {// 只有当stOut为空的时候,再从stIn里导入数据(导入stIn全部数据)if (stOut.empty()) {// 从stIn导入数据直到stIn为空while(!stIn.empty()) {stOut.push(stIn.top());stIn.pop();}}int result = stOut.top();stOut.pop();return result;}/** Get the front element. */int peek() {int res = this->pop(); // 直接使用已有的pop函数stOut.push(res); // 因为pop函数弹出了元素res,所以再添加回去return res;}/** Returns whether the queue is empty. */bool empty() {return stIn.empty() && stOut.empty();}
};

复杂度分析: 

  • 时间复杂度:push和empty为O(1), pop和peek为O(n)
  • 空间复杂度:O(n)

225. 用队列实现栈 

请你仅使用两个队列实现一个后入先出(LIFO)的栈,并支持普通栈的全部四种操作(pushtoppop 和 empty)。

实现 MyStack 类:

  • void push(int x) 将元素 x 压入栈顶。
  • int pop() 移除并返回栈顶元素。
  • int top() 返回栈顶元素。
  • boolean empty() 如果栈是空的,返回 true ;否则,返回 false 。

class MyStack {
public:queue<int> que;/** Initialize your data structure here. */MyStack() {}/** Push element x onto stack. */void push(int x) {que.push(x);}/** Removes the element on top of the stack and returns that element. */int pop() {int size = que.size();size--;while (size--) { // 将队列头部的元素(除了最后一个元素外) 重新添加到队列尾部que.push(que.front());que.pop();}int result = que.front(); // 此时弹出的元素顺序就是栈的顺序了que.pop();return result;}/** Get the top element. */int top() {return que.back();}/** Returns whether the stack is empty. */bool empty() {return que.empty();}
};

复杂度分析: 

  • 时间复杂度:pop为O(n),其他为O(1)
  • 空间复杂度:O(n)

20. 有效的括号

给定一个只包括 '('')''{''}''['']' 的字符串 s ,判断字符串是否有效。

有效字符串需满足:

  1. 左括号必须用相同类型的右括号闭合。
  2. 左括号必须以正确的顺序闭合。
  3. 每个右括号都有一个对应的相同类型的左括号。

代码示例:

class Solution {
public:bool isValid(string s) {if (s.size() % 2 != 0) return false; // 如果s的长度为奇数,一定不符合要求stack<char> st;for (int i = 0; i < s.size(); i++) {if (s[i] == '(') st.push(')');else if (s[i] == '{') st.push('}');else if (s[i] == '[') st.push(']');// 第三种情况:遍历字符串匹配的过程中,栈已经为空了,没有匹配的字符了,说明右括号没有找到对应的左括号 return false// 第二种情况:遍历字符串匹配的过程中,发现栈里没有我们要匹配的字符。所以return falseelse if (st.empty() || st.top() != s[i]) return false;else st.pop(); // st.top() 与 s[i]相等,栈弹出元素}// 第一种情况:此时我们已经遍历完了字符串,但是栈不为空,说明有相应的左括号没有右括号来匹配,所以return false,否则就return truereturn st.empty();}
};

复杂度分析: 

  • 时间复杂度:O(n)
  • 空间复杂度:O(n)

1047. 删除字符串中所有相邻重复项

给出由小写字母组成的字符串 S重复项删除操作会选择两个相邻且相同的字母,并删除它们。

在 S 上反复执行重复项删除操作,直到无法继续删除。

在完成所有重复项删除操作后返回最终的字符串。答案保证唯一。

代码示例:

法一:使用栈来存放

class Solution {
public:string removeDuplicates(string S) {stack<char> st;for (char s : S) {if (st.empty() || s != st.top()) {st.push(s);} else {st.pop(); // s 与 st.top()相等的情况}}string result = "";while (!st.empty()) { // 将栈中元素放到result字符串汇总result += st.top();st.pop();}reverse (result.begin(), result.end()); // 此时字符串需要反转一下return result;}
};

法二:拿字符串直接作为栈 

class Solution {
public:string removeDuplicates(string S) {string result;for(char s : S) {if(result.empty() || result.back() != s) {result.push_back(s);}else {result.pop_back();}}return result;}
};

复杂度分析: 

  • 时间复杂度:O(n)
  • 空间复杂度:O(n)

 150. 逆波兰表达式 

给你一个字符串数组 tokens ,表示一个根据 逆波兰表示法 表示的算术表达式。

请你计算该表达式。返回一个表示表达式值的整数。

注意:

  • 有效的算符为 '+''-''*' 和 '/' 。
  • 每个操作数(运算对象)都可以是一个整数或者另一个表达式。
  • 两个整数之间的除法总是 向零截断 。
  • 表达式中不含除零运算。
  • 输入是一个根据逆波兰表示法表示的算术表达式。
  • 答案及所有中间计算结果可以用 32 位 整数表示。

代码示例: 

class Solution {
public:int evalRPN(vector<string>& tokens) {// 力扣修改了后台测试数据,需要用longlongstack<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 类型并压入栈中}}int result = st.top();st.pop(); // 把栈里最后一个元素弹出(其实不弹出也没事)return result;}
};

复杂度分析: 

  • 时间复杂度:O(n)
  • 空间复杂度:O(n)

补充:

转换函数列表:

  1. stoi:将字符串转换为 int
  2. stol:将字符串转换为 long
  3. stoll:将字符串转换为 long long
  4. stoul:将字符串转换为 unsigned long
  5. stoull:将字符串转换为 unsigned long long
  6. stof:将字符串转换为 float
  7. stod:将字符串转换为 double
  8. stold:将字符串转换为 long double

347. 前K个高频元素 

给你一个整数数组 nums 和一个整数 k ,请你返回其中出现频率前 k 高的元素。你可以按 任意顺序 返回答案。

代码示例: 

class Solution {
public:// 小顶堆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) {// 要统计元素出现频率unordered_map<int, int> map; // map<nums[i],对应出现的次数>for (int i = 0; i < nums.size(); i++) {map[nums[i]]++;}// 对频率排序// 定义一个小顶堆,大小为kpriority_queue<pair<int, int>, vector<pair<int, int>>, mycomparison> pri_que;// 用固定大小为k的小顶堆,扫面所有频率的数值for (unordered_map<int, int>::iterator it = map.begin(); it != map.end(); it++) {pri_que.push(*it);if (pri_que.size() > k) { // 如果堆的大小大于了K,则队列弹出,保证堆的大小一直为kpri_que.pop();}}// 找出前K个高频元素,因为小顶堆先弹出的是最小的,所以倒序来输出到数组vector<int> result(k);for (int i = k - 1; i >= 0; i--) {result[i] = pri_que.top().first;pri_que.pop();}return result;}
};

复杂度分析:

  • 时间复杂度:O(nlogk)
  • 空间复杂度:O(n) 

补充:

 堆特性:

  • 优先队列:基于堆的数据结构,通常分为最大堆(max-heap)和最小堆(min-heap)。
    • 最大堆:父节点的值总是大于或等于其子节点的值。
    • 最小堆:父节点的值总是小于或等于其子节点的值。

区别总结: 

 

 参考如下:

代码随想录

http://www.lryc.cn/news/356963.html

相关文章:

  • 【教程】利用API接口添加本站同款【每日新闻早早报】-每天自动更新,不占用文章数量
  • 僵尸进程,孤儿进程,守护进程
  • Nuxt3 中使用 ESLint
  • 【Jmeter】性能测试之压测脚本生成,也可以录制接口自动化测试场景
  • Go 编程技巧:零拷贝字符串与切片转换的高效秘籍
  • 音视频开发—FFmpeg 音频重采样详解
  • 统计本地端口占用情况
  • 【MySQL精通之路】SQL优化(1)-查询优化(9)-外部联接优化
  • Python应用开发——30天学习Streamlit Python包进行APP的构建(1)
  • 轻兔推荐 —— 一个好用的软件服务推荐平台
  • LeetCode hot100-57-G
  • 基于Vue uni-app的自定义列表表格信息展示组件
  • 计网(部分在session学习章)
  • TypeScript 枚举
  • (1) 初识QT5
  • 2024年认证杯二阶段数学建模赛题浅析
  • Redis教程(十八):Redis的Redisson的看门狗机制
  • docker-compose 映射端口失败! docker端口映射失败 ,docker映射只能使用老端口,映射无法使用
  • AIGC笔记--基于PEFT库使用LoRA
  • yolo 算法 易主
  • 用这8种方法在海外媒体推广发稿平台上获得突破-华媒舍
  • 怎么调试前端文件:一步步揭开前端调试的神秘面纱
  • 【深入学习Redis丨第一篇】Redis服务器部署详解
  • git教程(IDEA + 命令行)
  • 树莓派部署harbor_arm64
  • Typora图床配置优化(PicGo-Core(command line) 插件 + gitee)
  • 开放式耳机推荐品牌:五款品质超凡机型必须选购
  • 【大数据面试题】31 Flink 有哪些重启方法
  • 【IDEA】Redis可视化神器
  • 深入分析 Android Activity (十一)