当前位置:网站首页>Stack / heap / queue question brushing (Part 1)
Stack / heap / queue question brushing (Part 1)
2022-07-22 17:48:00 【std i hurt o love】
One 、 Queues are implemented with two stacks
- push operation ,push To the end of the first stack
- pop The operation imports the elements of the first stack into the second stack , At this time, the data is in reverse order
- Pop up the top element of the second stack and make the return value , The implemented function is the same as that of queue, first in, first out
- Last , Then import the elements of the second stack back to the first stack , Ensure the original order of data
class Solution
{
public:
void push(int node) {
stack1.push(node);
}
int pop() {
while(!stack1.empty())
{
stack2.push(stack1.top());
stack1.pop();
}
int tmp=stack2.top();
stack2.pop();
while(!stack2.empty())
{
stack1.push(stack2.top());
stack2.pop();
}
return tmp;
}
private:
stack<int> stack1;
stack<int> stack2;
};
The complexity :push The time complexity of is O(1),pop The time complexity of is O(n),push Is directly added to the end of the stack , It is equivalent to traversing the stack twice
Spatial complexity :O(n), With the help of another auxiliary stack space
Two 、 contain min Function of the stack
Solution 1 : Double stack method ( recommend )
Add a minimum function to the original stack
It can't be used simply int Type variable record minimum ,
Because the data will pop, Maybe take the minimum pop fall , Therefore, it is necessary to record the minimum value synchronously , Record with a stack
class Solution {
public:
stack<int>s1;
stack<int>s2;// Record the minimum value at the top of the stack
void push(int value) {
s1.push(value);
if(s2.empty()||s2.top()>value)
s2.push(value);
else
s2.push(s2.top());
}
void pop() {
s1.pop();
s2.pop();// The minimum value changes synchronously
}
int top() {
return s1.top();
}
int min() {
return s2.top();
}
};
Time complexity :O(1), Every function access is a direct access , Acyclic
Spatial complexity :O(n),s1 For the necessary space ,s2 For auxiliary space
Solution 2 : Compression reduction
Use a stack to realize , The difference between the value stored in the stack memory and the minimum value , When smaller elements are encountered , The difference from the current minimum is negative , This is how _min The renewal of the value , When the top of the stack is negative , Subtract this assignment from the current minimum , That is, the minimum value of the previous data of the stack is restored .
The vulnerability of this method lies in the existence of numerical overflow , beyond INT_MAX or INT_MIN, It can pass here
class Solution {
public:
stack<int>s;
int _top,_min;
void push(int value) {
if(s.empty())// The minimum value is initialized to the first element
_min=value;
s.push(value-_min);// The difference between the stored data and the minimum data
if(value<_min)
_min=value;
_top=value;
}
void pop() {
if(!s.empty())
{
if(s.top()<0)
_min-=s.top();// When the top element of the stack is negative , representative pop minimum value , The minimum value needs to be updated
s.pop();
if(!s.empty())
_top=_min+(s.top()>0?s.top():0);
}
}
int top() {
return _top;
}
int min() {
return _min;
}
};
Time complexity :O(1), Each function access is O(1)
Spatial complexity :O(1), In addition to the necessary stack space , No extra space is used
3、 ... and 、 Valid parenthesis sequence
Solution 1 : Stack —— Left bracket in stack
Put the elements with left parentheses in the string on the stack , Brackets must match symmetrically , Do not cross , If the top of the stack is not the left bracket at this time, it will be handed in , Mismatch
class Solution {
public:
stack<char>sc;
bool isValid(string s) {
// write code here
for(int i=0;i<s.size();i++)
{
switch(s[i])
{
case '(':
case '[':
case '{':
sc.push(s[i]);
break;
case ')':
if(sc.empty()||sc.top()!='(')
return false;
sc.pop();
break;
case ']':
if(sc.empty()||sc.top()!='[')
return false;
sc.pop();
break;
case '}':
if(sc.empty()||sc.top()!='{')
return false;
sc.pop();
break;
}
}
return sc.empty();
}
};
Time complexity :O(n), Traversal string
Spatial complexity O(n), Auxiliary stack space
Solution 2 : Stack —— Right parenthesis on the stack ( recommend )
Again , Put the right bracket corresponding to the left bracket on the stack , Meet whether the right parenthesis match is equal
class Solution {
public:
stack<char>sc;
bool isValid(string s) {
// write code here
for(int i=0;i<s.size();i++)
{
if(s[i]=='(')
sc.push(')');
else if(s[i]=='[')
sc.push(']');
else if(s[i]=='{')
sc.push('}');
else
{
if(sc.empty()||s[i]!=sc.top())
return false;
sc.pop();
}
}
return sc.empty();
}
};
Time complexity :O(n), Traversal string
Spatial complexity O(n), Auxiliary stack space
边栏推荐
- DOM operation of JS - event chain (bubble target capture)
- 继承的详解
- Prepare for the attack and defense drill. Here is a security deployment map of Tencent!
- 2022-07-21:给定一个字符串str,和一个正数k, 你可以随意的划分str成多个子串, 目的是找到在某一种划分方案中,有尽可能多的回文子串,长度>=k,并且没有重合。 返回有几个回文子串。 来
- ES6 related interview question 2
- Ajout, suppression et modification de MySQL (niveau avancé)
- 关键路径问题
- NFS共享存儲服務
- 家庭琐事问题
- Conference OA project introduction & Conference release
猜你喜欢
秒杀实现图
Unity postprocess screen post-processing
How is VR panorama displayed in all walks of life? How to implement the application?
1312. Minimum number of inserts to make a string a palindrome string
奇瑞星途产品规划曝光,2.0t涡轮增压发动机,年底推出
Problems in CPD registration
Overview of nftfi track layout
win11怎么关闭触控板?win11关闭触控板的三种解决方法
关键路径实现
Win11怎么以管理员身份运行?Win11以管理员身份运行的设置方法
随机推荐
Misc进阶
Shell脚本案例---2
2022-07-21: given a string STR and a positive number k, you can divide STR into multiple substrings at will. The purpose is to find that in a certain division scheme, there are as many palindrome subs
Deep learning to achieve cross validation (image, signal processing)
MySQL constraint_ Non empty constraint
Buu misc advanced
使用 Abp.Zero 搭建第三方登录模块(四):微信小程序开发
指令安排问题
【单片机仿真项目】 外部中断0控制发光二极管亮灭
NFS shared storage service
MySQL系列文章之四:执行计划
DOM operation of JS - event chain (bubble target capture)
【HMS core】【FAQ】【Account Kit】典型问题合集1
PostgreSQL database is deployed on Linux server. Ms level is queried locally. Pgadmin installed on windows is used to query super slow for about 20s. Is it a network problem or a database configuratio
云主机性能测试方案
Misc advanced
354. Russian Doll envelope problem
基于 Flink CDC 实现海量数据的实时同步和转换
NFS共享存储服务
How does win11 close the touch pad? Three solutions for closing the touch panel in win11