基本定义:
先进后出为栈;先进先出为队列
栈的构造
#include<stdio.h>
#include<stack>
int main()
{
std::stack<int> S;
if(S.empty()) //判断栈是否为空
{
printf("S is empty!\n");
}
S.push(1);//压栈
S.push(6);
S.push(10);
printf("S.top:%d\n",S.top());//打印栈顶
S.pop();//出栈
S.pop();
printf("S.top: %d\n",S.top());
printf("S.size:%d\n",S.size());
return 0;
}
其中:
S.top():取出栈顶
S.empty():判断栈是否为空
S.push(x):将x添加至栈
S.pop()·弹出栈顶
S.size()栈的存储元素个数
队列的定义:
#include<stdio.h>
#include<queue>
int main()
{
std::queue<int> Q;
if(Q.empty())
{
printf("Q is empty!\n");
}
Q.push(1);//入队列
Q.push(6);
Q.push(10);
printf("Q.front:%d \n",Q.front());
Q.pop();
Q.pop();
printf("Q.front%d \n",Q.front());
printf("Q.size:%d\n",Q.size());
return 0;
}
其中:
Q.empty():判断队列是否为空
Q.front():返回队列头部元素
Q.back():返回队列尾部元素
Q.pop():出队列头部元素
Q.push(x):将×添加至队列
Q.size():返回队列的存储元素的个数
225.用队列实现栈:
使用队列实现栈的下列操作:
push(x) -- 元素 x 入栈
pop() -- 移除栈顶元素
top() -- 获取栈顶元素
empty() -- 返回栈是否为空
注意:
你只能使用队列的基本操作-- 也就是 push to back, peek/pop from front, size, 和 is empty 这些操作是合法的。
你所使用的语言也许不支持队列。 你可以使用 list 或者 deque(双端队列)来模拟一个队列 , 只要是标准的队列操作即可。
你可以假设所有操作都是有效的(例如, 对一个空的栈不会调用 pop 或者 top 操作)。
算法思路:
设置临时队列,进行压入队列的位置调换;
class MyStack {
public:
/** Initialize your data structure here. */
MyStack() {
}
/** Push element x onto stack. */
void push(int x) {
std::queue<int> temp_queue;
temp_queue.push(x);
while(!Q.empty())
{
temp_queue.push(Q.front());
Q.pop();
}
while(!temp_queue.empty())
{
Q.push(temp_queue.front());
temp_queue.pop();
}
}
/** Removes the element on top of the stack and returns that element. */
int pop() {
int x=Q.front();
Q.pop();
return x;
}
/** Get the top element. */
int top() {
return Q.front();
}
/** Returns whether the stack is empty. */
bool empty() {
return Q.empty();
}
private:
std::queue<int> Q;
};
/**
* 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();
*/
232:使用栈表示队列:
使用栈实现队列的下列操作:
push(x) -- 将一个元素放入队列的尾部。
pop() -- 从队列首部移除元素。
peek() -- 返回队列首部的元素。
empty() -- 返回队列是否为空。
示例:
MyQueue queue = new MyQueue();
queue.push(1);
queue.push(2);
queue.peek(); // 返回 1
queue.pop(); // 返回 1
queue.empty(); // 返回 false
说明:
你只能使用标准的栈操作 -- 也就是只有 push to top, peek/pop from top, size, 和 is empty 操作是合法的。
你所使用的语言也许不支持栈。你可以使用 list 或者 deque(双端队列)来模拟一个栈,只要是标准的栈操作即可。
假设所有操作都是有效的 (例如,一个空的队列不会调用 pop 或者 peek 操作)。
解法:
方法一:设置临时栈来实现顺序的调换
class MyQueue {
public:
/** Initialize your data structure here. */
MyQueue() {
}
/** Push element x to the back of queue. */
void push(int x) {
std::stack<int> temp_stack;
while(!S.empty())
{
temp_stack.push(S.top());
S.pop();
}
temp_stack.push(x);
while(!temp_stack.empty())
{
S.push(temp_stack.top());
temp_stack.pop();
}
}
/** Removes the element from in front of queue and returns that element. */
int pop() {
int x=S.top();
S.pop();
return x;
}
/** Get the front element. */
int peek() {
return S.top();
}
/** Returns whether the queue is empty. */
bool empty() {
return S.empty();
}
private:
std::stack<int> S;
};
/**
* 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();
方法二:双栈法:新建一个栈,用来pop操作
待完成
155.最小栈
设计一个支持 push ,pop ,top 操作,并能在常数时间内检索到最小元素的栈。
push(x) —— 将元素 x 推入栈中。
pop() —— 删除栈顶的元素。
top() —— 获取栈顶元素。
getMin() —— 检索栈中的最小元素。
示例:
输入:
["MinStack","push","push","push","getMin","pop","top","getMin"]
[[],[-2],[0],[-3],[],[],[],[]]
输出:
[null,null,null,null,-3,null,0,-2]
解释:
MinStack minStack = new MinStack();
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
minStack.getMin(); --> 返回 -3.
minStack.pop();
minStack.top(); --> 返回 0.
minStack.getMin(); --> 返回 -2.
解法:
class MinStack {
public:
/** initialize your data structure here. */
MinStack() {}
void push(int x) {
SS.push(x);
if(min_SS.empty())
{
min_SS.push(x);
}
else
{
if(x>min_SS.top())
{
x=min_SS.top();
}
min_SS.push(x);
}
}
void pop() {
SS.pop();
min_SS.pop();
}
int top() {
return SS.top();
}
int getMin() {
return min_SS.top();
}
private:
std::stack<int> SS;
std::stack<int> min_SS;
};
/**
* Your MinStack object will be instantiated and called as such:
* MinStack* obj = new MinStack();
* obj->push(x);
* obj->pop();
* int param_3 = obj->top();
* int param_4 = obj->getMin();
*/
1363(Poj) 合法的出栈序列
已 知 从 1 至 n 的 数字序列,按顺序入栈,每个数字入栈后即可出栈,也 可 在 栈 中 停 留 , 等 待 后 面 的 数 字 入 栈 出 栈 后 , 该 数 字 再 出 栈 , 求 该 数 字 序 列 的 出 栈 序 列 是 否 合 法 ?
思路:使用栈与队列模拟入栈出栈过程:
算法:1,将出栈序列存入队列中,1到n数字序列压入栈中;
2.每次将元素压入栈栈后与队列头部比较,相同则将队头和栈顶弹出;
3.依次进行若最后栈非空,则不合法
#include<stdio.h>
#include<queue>
#include<stack>
bool cheak_is_order(std::queue<int> &order)
{
std::stack<int> S;
int n = order.size();
for(int i = 1;i<=n;i++)
{
S.push(i);
while(!S.empty() && S.top()==order.front())
{
S.pop();
order.pop();
}
}
if(!S.empty())
{
return false;
}
return true;
}
int main()
{
int n;
int train;
scanf("%d",&n);
while(n)
{
scanf("%d",&train);
while(train)
{
std::queue<int> order;
order.push(train);
for(int i = 1;i<n;i++)
{
scanf("%d",&train);
}
if(cheak_is_order(order))
{
printf("Yes\n");
}
else{
printf("No\n");
}
scanf("%d",&train);
}
printf("\n");
scanf("%d",&n);
}
return 0;
}
224 简单计算器
实现一个基本的计算器来计算一个简单的字符串表达式的值。
字符串表达式可以包含左括号 ( ,右括号 ),加号 + ,减号 -,非负整数和空格 。
示例 1:
输入: "1 + 1"
输出: 2
示例 2:
输入: " 2-1 + 2 "
输出: 3
示例 3:
输入: "(1+(4+5+2)-3)+(6+8)"
输出: 23
预备知识:字符串转数字
void compute(std::stack<int> &number_stack,std::stack<char> &operation_stack)
{
if(number_stack.size()<2)
{
return;
}
int num2 = number_stack.top();
number_stack.pop();
int num1 = number_stack.top();
number_stack.pop();
if(operation_stack.top()=='+')
{
number_stack.push(num1+num2);
}
else if(operation_stack.top()=='-')
{
number_stack.push(num1-num2);
}
operation_stack.pop();
}
int main()
{
int number = 0;
std::string s="12345";
for(int i = 0;i<s.length();i++)
{
number = number * 10 +s[i] -'0';
}
printf("number = %d\n",number);
return 0;
}
字符串处理思路:
初始状态STATE_BEGIN
如果为数字字符,转入NUMBER_STATE
number=number*10+ch-'0';
否则,转入OPERATION_STATE;根据compute_flag进行计算
如果字符‘+’或者‘-’
压入OPERATION_STATE栈中,并将compute_flag设为1;
如果字符‘(’
设置compute_flag=0;
转入NUMBER_STATE;
如果‘)’进行compute计算
如果'0'到‘9’切换NUMBER_STATE;
void compute(std::stack<int> &number_stack,std::stack<char> &operation_stack)
{
if(number_stack.size()<2)
{
return;
}
int num2 = number_stack.top();
number_stack.pop();
int num1 = number_stack.top();
number_stack.pop();
int i=0;
if(operation_stack.top() == '+')
{
i=num1+num2;
number_stack.push(i);
}
else if(operation_stack.top() == '-')
{
i=num1-num2;
number_stack.push(i);
}
operation_stack.pop();
}
class Solution {
public:
int calculate(string s) {
const int STATE_BEGIN=0;
const int STATE_NUMBER=1;
const int STATE_OPERATOR=2;
std::stack<int> number_stack;
std::stack<char> operation_stack;
int compute_flag=0;
int number = 0;
int STATE = STATE_BEGIN;
for(int i = 0;i<s.length();i++)
{
if(s[i]=' ')
{
continue;
}
switch(STATE)
{
case STATE_BEGIN:
if(s[i]>='0'&& s[i]<='9')
{
STATE=STATE_NUMBER;
}
else{
STATE=STATE_OPERATOR;
}
i--;
break;
case STATE_NUMBER:
if(s[i]>='0'&&s[i]<='9')
{
number=number*10+(s[i]-'0');
}
else
{
number_stack.push(number);
if(compute_flag==1)
{
compute(number_stack,operation_stack);
}
number = 0;
i--;
STATE=STATE_OPERATOR;
}
break;
case STATE_OPERATOR:
if(s[i]=='+'||s[i]=='-')
{
operation_stack.push(s[i]);
compute_flag=1;
}
else if(s[i]=='(')
{
STATE=STATE_NUMBER;
compute_flag=0;
}
else if(s[i]>='0'&&s[i]<='9')
{
STATE=STATE_NUMBER;
i--;
}
else if(s[i]==')')
{
//compute_flag=1;
compute(number_stack,operation_stack);
}
break;
}
}
if(number!=0)
{
number_stack.push(number);
compute(number_stack,operation_stack);
}
if(number==0 && number_stack.empty())
{
return 1;
}
return number_stack.top();
}
};
215.数组中第K个大的数
在未排序的数组中找到第 k 个最大的元素。请注意,你需要找的是数组排序后的第 k 个最大的元素,而不是第 k 个不同的元素。
示例 1:
输入: [3,2,1,5,6,4] 和 k = 2
输出: 5
示例 2:
输入: [3,2,3,1,2,4,5,5,6] 和 k = 4
输出: 4
第一种方法:排序算法:
bool cmp(int a,int b)
{
return a>b;
}
class Solution {
public:
int findKthLargest(vector<int>& nums, int k) {
std::sort(nums.begin(),nums.end(),cmp);
return nums[k-1];
}
};
方法二 最小堆
预备知识:优先级队列:普通的队列是一种先进先出的数据结构,元素在队列尾追加,而从队列头删除。在优先队列中,元素被赋予优先级。当访问元素时,具有最高优先级的元素最先删除。优先队列具有最高级先出 (first in, largest out)的行为特征。
定义:priority_queue<Type, Container, Functional>
Type 就是数据类型,Container 就是容器类型(Container必须是用数组实现的容器,比如vector,deque等等,但不能用 list。STL里面默认用的是vector),Functional 就是比较的方式。
完全二叉树:若二叉树的深度为h,则除第h层外,其他层的结点全部达到最大值,且第h层的所有结点都集中在左子树
二叉堆:最大(小)值先出的完全二叉树
堆是一颗完全二叉树;堆中的某个结点的值总是大于等于(最大堆)或小于等于(最小堆)其孩子结点的值;堆中每个结点的子树都是堆树。
最大堆的构造
#include<stdio.h>
#include<queue>
int main()
{
std::priority_queue<int> big_heap; //默认构造的是最大堆
std::priority_queue<int,std::vector<int>,std::greater<int>> small_heap;
std::priority_queue<int,std::vector<int>,std::less<int>> big_heap2;
if(big_heap.empty())
{
printf("big_heap is empty!\n");
}
int test[]={6,10,1,7,99,4,33};
for(int i = 0;i<7;i++)
{
big_heap.push(test[i]);
}
printf("big_heap.top=%d\n",big_heap.top());
big_heap.push(1000);
printf("big_heap.top=%d\n",big_heap.top());
for(int i = 0;i<3 ;i++)
{
big_heap.pop();
}
printf("big_heap.top=%d\n",big_heap.top());
printf("big_heap.size = %d\n",big_heap.size());
return 0;
}
解题思路:
维护一个最小堆,将比第k个大的数push入堆中,则栈顶即为第k个大的数
class Solution {
public:
int findKthLargest(vector<int>& nums, int k) {
std::priority_queue<int,std::vector<int>,std::greater<int>> small_heap;
for(int i=0;i<nums.size();i++)
{
if(small_heap.size()<k)
{
small_heap.push(nums[i]);
}
else if(small_heap.top()<nums[i])
{
small_heap.pop();
small_heap.push(nums[i]);
}
}
return small_heap.top();
}
};
295.数据流中位数
中位数是有序列表中间的数。如果列表长度是偶数,中位数则是中间两个数的平均值。
例如,
[2,3,4] 的中位数是 3
[2,3] 的中位数是 (2 + 3) / 2 = 2.5
设计一个支持以下两种操作的数据结构:
void addNum(int num) - 从数据流中添加一个整数到数据结构中。
double findMedian() - 返回目前所有元素的中位数。
示例:
addNum(1)
addNum(2)
findMedian() -> 1.5
addNum(3)
findMedian() -> 2
算法思路:
设置一个最大堆和最小堆,分别各自存放一半数据,则中位数即为堆顶
class MedianFinder {
public:
/** initialize your data structure here. */
MedianFinder() {
}
void addNum(int num) {
if(big_heap.empty())
{
big_heap.push(num);
return; //注意当big_heap初始化后需要返回,否则可能会重复压入num
}
if(big_heap.size()==small_heap.size())
{
if(num<big_heap.top())
{
big_heap.push(num);
}
else
{
small_heap.push(num);
}
}
else if(big_heap.size()<small_heap.size())
{
if(num<small_heap.top())
{
big_heap.push(num);
}
else
{
big_heap.push(small_heap.top());
small_heap.pop();
small_heap.push(num);
}
}
else if(big_heap.size()>small_heap.size())
{
if(num>big_heap.top())
{
small_heap.push(num);
}
else{
small_heap.push(big_heap.top());
big_heap.pop();
big_heap.push(num);
}
}
}
double findMedian() {
if(big_heap.size()==small_heap.size())
{
return (big_heap.top()+small_heap.top())*0.5;
}
else if(big_heap.size()>small_heap.size())
{
return big_heap.top();
}
else
{
return small_heap.top();
}
}
private:
std::priority_queue<int,std::vector<int>,std::greater<int>> small_heap;
std::priority_queue<int,std::vector<int>,std::less<int>> big_heap;
};
/**
* Your MedianFinder object will be instantiated and called as such:
* MedianFinder* obj = new MedianFinder();
* obj->addNum(num);
* double param_2 = obj->findMedian();
*/