用栈实现队列
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函数,this函数用于调用成员函数
stOut.push(res); // 因为pop函数弹出了元素res,所以再添加回去
return res;
}
/** Returns whether the queue is empty. */
bool empty() {
return stIn.empty() && stOut.empty();
}
};
用队列实现栈
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();
}
};
有效的括号
https://leetcode.cn/problems/valid-parentheses/
给定一个只包括 '(',')','{','}','[',']' 的字符串,判断字符串是否有效。
有效字符串需满足:
左括号必须用相同类型的右括号闭合。
左括号必须以正确的顺序闭合。
注意空字符串可被认为是有效字符串。
思路:
括号匹配是使用栈解决的经典问题。
题意其实就像我们在写代码的过程中,要求括号的顺序是一样的,有左括号,相应的位置必须要有右括号。其中,如果左右括号不匹配,我们可以想到三种情况:
左边括号多了
右边括号多了
左右不匹配
针对这三种问题,通过栈来解决的话可以将问题转换为:
遍历完后栈不为空
遍历途中栈空了
遍历途中栈顶和遍历的值不匹配。
代码如下:
class Solution {
public:
bool isValid(string s) {
stack<int> 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('}');
else if(st.empty() || s[i] != st.top()) return false;//情况2.3
else {
st.pop();
}
}
return st.empty();//情况1
}
};
删除字符串中的所有相邻重复项
给出由小写字母组成的字符串 S,重复项删除操作会选择两个相邻且相同的字母,并删除它们。
在 S 上反复执行重复项删除操作,直到无法继续删除。
在完成所有重复项删除操作后返回最终的字符串。答案保证唯一。
思路:因为题目中提到反复删除重复项,还是考虑使用栈,遍历字符串入栈,判断字符串遍历的位置是否和栈内相等,如果相等就pop,如果不等就入栈。
class Solution {
public:
string removeDuplicates(string S) {
string result;
for(char s : S){
if(result.empty() || s != result.back()){
result.push_back(s);
}
else{
result.pop_back();
}
}return result;
}
};
逆波兰表达式求值
根据 逆波兰表示法,求表达式的值。
有效的运算符包括 + , - , * , / 。每个运算对象可以是整数,也可以是另一个逆波兰表达式。
思路:通过压栈与弹出进行 解答。
代码:
class Solution {
public:
int evalRPN(vector<string>& tokens) {
stack <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(num1 + num2);
if(tokens[i] == "-") st.push(num2 - num1);
if(tokens[i] == "*") st.push(num1 * num2);
if(tokens[i] == "/") st.push(num2 / num1);
}else{
st.push(stoll(tokens[i]));//注意这里要进行格式转换
}
}
long long result = st.top();
return result;
}
};
前 K 个高频元素
给定一个非空的整数数组,返回其中出现频率前 k 高的元素。
示例 1:
输入: nums = [1,1,1,2,2,3], k = 2
输出: [1,2]
示例 2:
输入: nums = [1], k = 1
输出: [1]
思路:根据卡哥的这张图,可以把整体思路捋清楚:
首先我们要使用map进行查找,查找出现的数值(key)和出现的次数(value),当我们得到了出现的数值和次数的时候,我们使用优先级队列,按照出现的次数 进行排序。
这里我们简单解释一下优先级队列和使用方式:
优先级队列:priority_queue:用法和queue基本相同。
top 访问队头元素
empty 队列是否为空
size 返回队列内元素个数
push 插入元素到队尾 (并排序)
emplace 原地构造一个元素并插入队列
pop 弹出队头元素
swap 交换内容
优先队列声明:
priority_queue<type,container,function>
其中第一个参数不可以省略,后两个参数可以省略。
type:数据类型
container:实现优先队列的底层容器,要求必须是以数组形式实现的容器
function:元素之间的比较方式
priority_queue<int> q;//定义一个优先队列,按照元素从大到小的顺序出队
//等同于
priority_queue<int,vector<int>, less<int> >q;
//另外一种按元素从小到大顺序出队
priority_queue<int,vector<int>, greater<int> >q;
注意上述情况只应用于默认,像这道题就没法使用(因为有key和value两个数值)需要自己去定义元素间比较方式(具体定义方法见3)
使用方法示例:
priority_queue<int> q;
//将元素入队
q.push(1);
q.push(2);
q.push(3);
while(!q.empty()){
cout<<q.top()<<endl;//输出队首元素
q.pop();//出队
}
//从大到小依次输出3 2 1
3、
347. 前 K 个高频元素在用map对数字出现个数进行统计之后,用到优先级队列,定义为:
priority_queue<pair<int, int>, vector<pair<int, int>>, mycomparison> pri_que;
其中:mycomparison定义为(小顶堆):
class mycomparison {
public:
bool operator()(const pair<int, int>& lhs, const pair<int, int>& rhs) {
return lhs.second > rhs.second;
//bool operator()使用了重载操作符,可以对两个pair进行比较,这里和一般的快排思路相反,l>r,但是表示从小到大
}
};
这里使用了结构体内嵌比较函数,相对于普通的比较函数,内嵌式的速度更快,而且如果存在多种结构的比较,内嵌式也显得更清爽。
这里解释一下pair函数:
类模板:template<class T1,class T2> struct pair
参数:T1是第一个值的数据类型,T2是第二个值的数据类型。
功能:pair将一对值(T1和T2)组合成一个值,
这一对值可以具有不同的数据类型(T1和T2),
两个值可以分别用pair的两个公有函数first和second访问。
代码如下:
// 时间复杂度:O(nlogk)
// 空间复杂度:O(n)
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]]++;
}
// 对频率排序
// 定义一个小顶堆,大小为k
priority_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,则队列弹出,保证堆的大小一直为k
pri_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;
}
};