232. 用栈实现队列
主要就是理解栈和队列的特性。
用两个栈来模拟,其目的就是为了颠倒排列顺序
class MyQueue {
public:
stack<int> in_stack;
stack<int> out_stack;
MyQueue() {
}
void push(int x) {
in_stack.push(x);
}
int pop() {
int result = peek();
out_stack.pop();
return result;
}
int peek() {
if(out_stack.empty()) {
while(!in_stack.empty()) {
out_stack.push(in_stack.top());
in_stack.pop();
}
}
int result = out_stack.top();
return result;
}
bool empty() {
return in_stack.empty()&&out_stack.empty();
}
};
20. 有效的括号
括号配对要想到使用栈
class Solution {
public:
bool isValid(string s) {
if(s.length()%2==1)return false;
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(']');
else if(st.empty() || st.top()!=s[i])return false;
else st.pop();
}
return st.empty();
}
};
1047. 删除字符串中的所有相邻重复项
class Solution {
public:
string removeDuplicates(string s) {
stack<char> a;
string result;
if(s=="")return s;
for(char i:s) {
if(a.empty() || i != a.top()) {
a.push(i);
}else {
a.pop();
}
}
while(!a.empty()) {
result+=a.top();
a.pop();
}
reverse(result.begin(),result.end());
return result;
}
};
150. 逆波兰表达式求值
主要是了解波兰表达式的特性,思路知道用栈了就还是很简单的
class Solution {
public:
int evalRPN(vector<string>& tokens) {
stack<long long> s;
for(int i=0;i<tokens.size();i++) {
if(tokens[i] == "+"||tokens[i] =="-"||tokens[i] == "*"||tokens[i] =="/") {
long long num1 = s.top();
s.pop();
long long num2 = s.top();
s.pop();
if(tokens[i]=="+")s.push(num2+num1);
if(tokens[i]=="-")s.push(num2-num1);
if(tokens[i]=="*")s.push(num2*num1);
if(tokens[i]=="/")s.push(num2/num1);
}else {
s.push(stoll(tokens[i])); //stoll() 转换为长整型
}
}
int result = s.top();
s.pop();
return result;
}
};
*239. 滑动窗口最大值
听巧妙的方法但从中找不出什么共性
class MyQueue {
public:
deque<int> que;
void pop(int value) {
if(!que.empty()&&value == que.front()) {
que.pop_front();
}
}
void push(int value) {
while(!que.empty() && value >que.back()) {
que.pop_back();
}
que.push_back(value);
}
int front() {
return que.front();
}
};
class Solution {
public:
vector<int> maxSlidingWindow(vector<int>& nums, int k) {
MyQueue que;
vector<int> result;
for(int i=0;i<k;i++) {
que.push(nums[i]);
}
result.push_back(que.front());
for(int i=k;i<nums.size();i++) {
que.pop(nums[i-k]);
que.push(nums[i]);
result.push_back(que.front());
}
return result;
}
};
347. 前 K 个高频元素
需要重刷,搞懂priority_que的实现,
class myComparsion {
public:
bool operator()(const pair<int,int>&a,const pair<int,int>&b) {
return a.second>b.second;
}
};
class Solution {
public:
vector<int> topKFrequent(vector<int>& nums, int k) {
unordered_map<int,int> map;
for(int i=0;i<nums.size();i++) {
map[nums[i]]++;
}
//对于优先队列来说,当比较函数返回true时,表示第一个参数(这里是lhs)的优先级更低,第二个参数(这里是rhs)的优先级更高。
priority_queue<pair<int,int>,vector<pair<int,int>>,myComparsion> pri;
for(unordered_map<int,int>::iterator it=map.begin();it!=map.end();it++) {
pri.push(*it);
if(pri.size()>k) {
pri.pop();
}
}
vector<int> result(k);
for(int i=k-1;i>=0;i--) {
result[i] = pri.top().first;
pri.pop();
}
return result;
}
};