栈与队列
- C++中stack 是容器么?
- 我们使用的stack是属于哪个版本的STL?
- 我们使用的STL中stack是如何实现的?
- stack 提供迭代器来遍历stack空间么?
1、stack是容器适配器。C++中,vector和list才是容器。
2、SGI版本。
3、SGI STL中 队列底层实现缺省情况下一样使用deque实现的。
4、不提供迭代器。因为只能先进后出。
232.用栈实现队列
题意: 请你仅使用两个栈实现先入先出队列。队列应当支持一般队列支持的所有操作(push、pop、peek、empty):
实现 MyQueue 类:
void push(int x) 将元素 x 推到队列的末尾
int pop() 从队列的开头移除并返回元素
int peek() 返回队列开头的元素
boolean empty() 如果队列为空,返回 true ;否则,返回 false
说明:
你 只能 使用标准的栈操作 —— 也就是只有 push to top, peek/pop from top, size, 和 is empty 操作是合法的。
你所使用的语言也许不支持栈。你可以使用 list 或者 deque(双端队列)来模拟一个栈,只要是标准的栈操作即可。
解法: 将push搞好。每次push数据,都先放进st1,再从st1放进st2。
class MyQueue {
public:
MyQueue() {
st1 = {};
st2 = {};
}
void push(int x) {
while(!st2.empty()){
int tmp = st2.top();
st2.pop();
st1.push(tmp);
}
st1.push(x);
while(!st1.empty()){
int tmp = st1.top();
st1.pop();
st2.push(tmp);
}
}
int pop() {
int tmp = st2.top();
st2.pop();
return tmp;
}
int peek() {
return st2.top();
}
bool empty() {
return st2.empty();
}
private:
stack<int> st1;
stack<int> st2;
};
/**
* Your MyQueue object will be instantiated and called as such:
* MyQueue* obj = new MyQueue();
* obj->push(x);
* int param_2 = obj->pop();
* int param_3 = obj->peek();
* bool param_4 = obj->empty();
*/
225. 用队列实现栈
题意: 请你仅使用两个队列实现一个后入先出(LIFO)的栈,并支持普通栈的全部四种操作(push、top、pop 和 empty)。
实现 MyStack 类:
void push(int x) 将元素 x 压入栈顶。
int pop() 移除并返回栈顶元素。
int top() 返回栈顶元素。
boolean empty() 如果栈是空的,返回 true ;否则,返回 false 。
注意:
你只能使用队列的基本操作 —— 也就是 push to back、peek/pop from front、size 和 is empty 这些操作。
你所使用的语言也许不支持队列。 你可以使用 list (列表)或者 deque(双端队列)来模拟一个队列 , 只要是标准的队列操作即可。
解法: 将push和pop搞好。理解为q2只放一个栈顶元素,那么每次push,都要把q2数据放到q1;pop的时候,直接将q2的数据作为pop返回的数据,然后将q1的数据都放进q2,再将q2的数据放回q1,不过要剩下一个,仍然作为栈顶元素。
class MyStack {
public:
MyStack() {
}
void push(int x) {
if(!q2.empty()){
int tmp = q2.front();
q2.pop();
q1.push(tmp);
}
q2.push(x);
}
int pop() {
int tmp = -1;
if(!q2.empty()){
tmp = q2.front();
q2.pop();
while(!q1.empty()){
int tmp2 = q1.front();
q1.pop();
q2.push(tmp2);
}
while(!q2.empty() && q2.size() - 1){
int tmp2 = q2.front();
q2.pop();
q1.push(tmp2);
}
}
return tmp;
}
int top() {
if(!q2.empty()) return q2.front();
return -1;
}
bool empty() {
return q2.empty();
}
private:
queue<int> q1;
queue<int> q2;
};
/**
* Your MyStack object will be instantiated and called as such:
* MyStack* obj = new MyStack();
* obj->push(x);
* int param_2 = obj->pop();
* int param_3 = obj->top();
* bool param_4 = obj->empty();
*/
20. 有效的括号
题意: 给定一个只包括 ‘(’,‘)’,‘{’,‘}’,‘[’,‘]’ 的字符串 s ,判断字符串是否有效。
有效字符串需满足:
左括号必须用相同类型的右括号闭合。
左括号必须以正确的顺序闭合。
每个右括号都有一个对应的相同类型的左括号。
解法: 用栈存左括号,然后检查到右括号的时候,看看栈顶的左括号对不对劲,对劲就弹出。
class Solution {
public:
bool isValid(string s) {
// if(s.size() % 2 != 0) return false;
stack<char> st;
for(int i = 0; i < s.size(); i++){
if(s[i] == '(' || s[i] == '[' || s[i] == '{'){
st.push(s[i]);
}
else if(s[i] == '}'){
if(st.empty() || st.top() != '{') return false;
else st.pop();
}
else if(s[i] == ')'){
if(st.empty() || st.top() != '(') return false;
else st.pop();
}
else if(s[i] == ']'){
if(st.empty() || st.top() != '[') return false;
else st.pop();
}
}
if(!st.empty()) return false;
return true;
}
};
1047. 删除字符串中的所有相邻重复项
题意: 给出由小写字母组成的字符串 S,重复项删除操作会选择两个相邻且相同的字母,并删除它们。
在 S 上反复执行重复项删除操作,直到无法继续删除。
在完成所有重复项删除操作后返回最终的字符串。答案保证唯一。
解法: 匹配问题用栈。
注意:栈里返回的元素是从栈顶到栈底的,要reverse才能变为正序;并且reverse函数的返回值是void。
class Solution {
public:
string removeDuplicates(string s) {
stack<char> st;
for(char c : s){
if(!st.empty() && c == st.top()) st.pop();
else st.push(c);
}
string result = "";
while(!st.empty()){
char c = st.top();
result += c;
st.pop();
}
reverse(result.begin(), result.end());
return result;
}
};
150. 逆波兰表达式求值
题意: 给你一个字符串数组 tokens ,表示一个根据 逆波兰表示法 表示的算术表达式。
请你计算该表达式。返回一个表示表达式值的整数。
注意:
有效的算符为 ‘+’、‘-’、‘*’ 和 ‘/’ 。
每个操作数(运算对象)都可以是一个整数或者另一个表达式。
两个整数之间的除法总是 向零截断 。
表达式中不含除零运算。
输入是一个根据逆波兰表示法表示的算术表达式。
答案及所有中间计算结果可以用 32 位 整数表示。
解法: 栈。若为运算符,则弹出栈内的两个数字;若不为运算符,则将字符串转为数字(stoi将字符串转为int),然后放入栈内。
class Solution {
public:
int evalRPN(vector<string>& tokens) {
stack<int> st;
for(string c : tokens){
if(c == "+" || c == "-" || c == "*" || c == "/"){
int n2 = st.top();
st.pop();
int n1 = st.top();
st.pop();
int result = 0;
if(c == "+") result = n1 + n2;
else if(c == "-") result = n1 - n2;
else if(c == "*") result = n1 * n2;
else if(c == "/") result = (int) n1 / n2;
st.push(result);
} else{
int num = stoi(c);
st.push(num);
}
}
return st.top();
}
};
239. 滑动窗口最大值
deque和queue的区别:deque是双端队列,queue是单端队列。
题意: 给你一个整数数组 nums,有一个大小为 k 的滑动窗口从数组的最左侧移动到数组的最右侧。你只可以看到在滑动窗口内的 k 个数字。滑动窗口每次只向右移动一位。
返回 滑动窗口中的最大值 。
解法: 用双端队列定义一个从队头到队尾单调递减的队列类。
class Solution {
private:
// 定义一个从队头到队尾单调递减的队列类
class Mydeque{
public:
deque<int> que;
void pop(int val){
if(!que.empty() && val == que.front()){
que.pop_front();
}
}
void push(int val){
while(!que.empty() && val > que.back()){
que.pop_back();
}
que.push_back(val);
}
int front(){
return que.front();
}
};
public:
vector<int> maxSlidingWindow(vector<int>& nums, int k) {
Mydeque q;
vector<int> result;
for(int i = 0; i < k; i++){
q.push(nums[i]);
}
result.push_back(q.front());
for(int i = k; i < nums.size(); i++){
q.pop(nums[i - k]);
q.push(nums[i]);
result.push_back(q.front());
}
return result;
}
};
347.前 K 个高频元素
题意: 给你一个整数数组 nums
和一个整数 k
,请你返回其中出现频率前 k
高的元素。你可以按 任意顺序 返回答案。
提示:
1 <= nums.length <= 105
k 的取值范围是 [1, 数组中不相同的元素的个数]
题目数据保证答案唯一,换句话说,数组中前 k 个高频元素的集合是唯一的。
解法: 小顶堆法。这个小顶堆可以用优先级队列实现。
// mycomparison类和priority_queue结合,表示小顶堆。
// mycomparison类里面定义了()的操作符重载
class mycomparison{
bool operator()(const pair<int, int>& lhs, const pair<int, int>& rhs){
return lhs.second > rhs.second;
}
};
priority_queue<pair<int, int>, vector<pair<int, int>>, mycomparison> pri_que;
// c++优先队列priority_queue(自定义比较函数):
// https://blog.csdn.net/qq_21539375/article/details/122128445
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;
for(int i = 0; i < nums.size(); i++) map[nums[i]]++;
// 小顶堆
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) pri_que.pop();
}
vector<int> result;
while(!pri_que.empty()){
result.push_back(pri_que.top().first); // 因为放进去的是一个指针。取元素,需要用.。
pri_que.pop();
}
return result;
}
};
参考:
1、代码随想录/栈与队列。