14算法 .栈和队列
1.通过队列实现栈 LeetCode 225
a.两个队列实现栈
class MyStack {
public:
queue<int> q1, q2;
MyStack() {
}
void push(int x) {
if(q1.empty()){
q2.push(x);
return;
}
if(q2.empty()){
q1.push(x);
return;
}
}
int pop() {
int t;
if(q1.empty()){
if(q2.size() == 1){
t = q2.front();
q2.pop();
return t;
}
else{
while(q2.size() > 1){
q1.push(q2.front());
q2.pop();
}
t = q2.front();
q2.pop();
return t;
}
}
if(q2.empty()){
if(q1.size() == 1){
t = q1.front();
q1.pop();
return t;
}
else{
while(q1.size() > 1){
q2.push(q1.front());
q1.pop();
}
t = q1.front();
q1.pop();
return t;
}
}
return 0;
}
int top() {
if(q1.empty())
return q2.back();
else
return q1.back();
}
bool empty() {
return q1.empty() && q2.empty();
}
};
b.单队列实现栈
class MyStack {
public:
MyStack() = default;
void push(int x) {
que.push(x);
int n = que.size();
for (int i = 0; i + 1 < n; i++) {
que.push(que.front());
que.pop();
}
}
int pop() {
int val = top();
que.pop();
return val;
}
int top() {
return que.front();
}
bool empty() {
return que.empty();
}
private:
queue<int> que;
};
232 两个栈实现队列
#include<stack>
class MyQueue {
public:
/** Initialize your data structure here. */
MyQueue() {
}
/** Push element x to the back of queue. */
void push(int x) {
while(s2.size()>0)
{
s1.push(s2.top());
s2.pop();
}
s1.push(x);
}
/** Removes the element from in front of queue and returns that element. */
int pop() {
while(s1.size()>0)
{
s2.push(s1.top());
s1.pop();
}
int a=s2.top();
s2.pop();
return a;
}
/** Get the front element. */
int peek() {
while(s1.size()>0)
{
s2.push(s1.top());
s1.pop();
}
int a=s2.top();
return a;
}
/** Returns whether the queue is empty. */
bool empty() {
return s1.empty()&&s2.empty();
}
private:
stack<int > s1,s2;//s1输入栈 s2 输出栈
};
155 最小值栈
class MinStack {
public:
/** initialize your data structure here. */
MinStack() {
}
void push(int x) {
if(s1.empty())
{
s1.push(x);
small.push(x);
}
else
{
if(x>small.top())
{
small.push(small.top());
}
else{
small.push(x);
}
s1.push(x);
}
}
void pop() {
s1.pop();
small.pop();
}
int top() {
return s1.top();
}
int getMin() {
return small.top();
}
private:
stack<int > small;
stack<int> s1;
};
946合法的输出栈序列
class Solution {
public:
bool validateStackSequences(vector<int>& pushed, vector<int>& popped) {
stack<int> s;
int k = 0;
for(auto n : pushed)
{
s.push(n);
while(!s.empty() && s.top() == popped[k])
{
s.pop();
++k;
}
}
return s.empty();
}
};
224简单的计算器
class Solution {
public:
int calculate(string s) {
stack<int> ops;
ops.push(1);
int sign = 1;
int ret = 0;
int n = s.length();
int i = 0;
while (i < n) {
if (s[i] == ' ') {
i++;
} else if (s[i] == '+') {
sign = ops.top();
i++;
} else if (s[i] == '-') {
sign = -ops.top();
i++;
} else if (s[i] == '(') {
ops.push(sign);
i++;
} else if (s[i] == ')') {
ops.pop();
i++;
} else {
long num = 0;
while (i < n && s[i] >= '0' && s[i] <= '9') {
num = num * 10 + s[i] - '0';
i++;
}
ret += sign * num;
}
}
return ret;
}
};
``
215 数组中第K大的数
```cpp
#include<queue>
class Solution {
public:
int findKthLargest(vector<int>& nums, int k) {
std::priority_queue<int,std::vector<int>,std::greater<int>> small_heap;
int i=0;
for(i=0;i<nums.size();i++)
{
if(i<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();
}
};
STL优先级队列(二叉堆) (STL)
#include
std::priority_queue big_heap // 默认构造是最大堆
std::priority_queue<int,std::vector,std::greater> smalll_heap; //最小堆构造方法
std::priority_queue<int,std::vector,std::less> smalll_heap; //最大堆构造方法
big_heap.empty();【判断堆是否为空】
big_heap.pop();弹出对顶元素 最大值
big_heap.push(x);将元素x添加到二叉堆
big_heap.top() ;返回堆顶元素
big_heap.size() ;返回堆中元素的个数
堆是一种数据结构,他的特点在于形成某种优先的结构。在计算机经常用到,比如优先队列,或者是优先进程管理。
堆(也叫二叉堆)的性质:
1、任何一个节点,都不大于他的父亲节点。
2、必须是一颗完全二叉树。
#define _CRT_SECURE_NO_WARNINGS 1
#include <stdio.h>
#include <assert.h>
#include <stdlib.h>
typedef int HeapDataType;
typedef struct MaxHeap{
HeapDataType* data;
int count;
int MaxSize;
}MH;
//-----------堆的构建等等方法
int size(MH *mh);//返回堆大小
int isEmpty(MH *mh);//判空
void initMaxHeap(MH* mh, int size);//初始化堆
void initMaxHeap2(MH* mh, int size, HeapDataType* arr);//第二种初始化堆,heapify算法
void AdjustUp(MH* mh, int k);//上移元素
void AdjustDown(MH* mh, int k);//下移操作
void insertMaxHeap(MH* mh, HeapDataType value);//插入元素
HeapDataType TopK(MH* mh);//弹出元素
void TestMaxHeap();//测试函数
堆:
#include "MH.h"
//返回堆大小
int size(MH *mh){
return mh->count;
}
//判空
int isEmpty(MH *mh){
return 0 == mh->count;
}
//下移
void AdjustDown(MH* mh, int k){
while (k * 2 <= mh->count)
{
int j = k * 2;
if (j + 1 <= mh->count && mh->data[j] < mh->data[j + 1])//如果右孩子存在且右孩子比左孩子大
{
j = j + 1;
}
if (mh->data[k] > mh->data[j])//如果节点比孩子大
{
break;
}
//否则交换k和j
int tmp = mh->data[k];
mh->data[k] = mh->data[j];
mh->data[j] = tmp;
k = j;
}
}
//初始化堆
void initMaxHeap(MH* mh, int size){
mh->MaxSize = size;
mh->data = (HeapDataType*)malloc((mh->MaxSize + 1) * sizeof(HeapDataType));//从1开始存储
mh->count = 0;
}
//第二种初始化堆,heapify算法
void initMaxHeap2(MH* mh, int size, HeapDataType* arr){
mh->MaxSize = size;
mh->data = (HeapDataType*)malloc((mh->MaxSize + 1) * sizeof(HeapDataType));//从1开始存储
//吧arr数组的值赋给这个堆
for (int i = 0; i < size; i++)
{
mh->data[i + 1] = arr[i];
}
mh->count = size;
//整合堆操作
for (int i = mh->count / 2; i > 0; i--)
{
AdjustDown(mh, i);
}
}
//上移元素
void AdjustUp(MH* mh, int k){
while (1 < k && mh->data[k / 2] < mh->data[k])
{
int tmp = mh->data[k / 2];
mh->data[k / 2] = mh->data[k];
mh->data[k] = tmp;
k /= 2;
}
}
//插入元素
void insertMaxHeap(MH* mh, HeapDataType value){
//看看有没有满
assert(mh->count + 1 <= mh->MaxSize);
//count为最后一个元素
mh->data[mh->count + 1] = value;
mh->count++;
AdjustUp(mh,mh->count);//上移到合适位置
}
//弹出元素
HeapDataType TopK(MH* mh){
assert(mh->count > 0);
//获得顶端元素
HeapDataType res = mh->data[1];
//把最后的赋值给顶端
mh->data[1] = mh->data[mh->count];
//最后的元素置0,并且count--
mh->data[(mh->count)--] = 0;
//把顶端元素下移到合适位置
AdjustDown(mh, 1);
return res;
}
void TestMaxHeap()
{
MH mh;
initMaxHeap(&mh, 10);
insertMaxHeap(&mh, 2);
insertMaxHeap(&mh, 1);
insertMaxHeap(&mh, 3);
insertMaxHeap(&mh, 5);
insertMaxHeap(&mh, 4);
for (int i = 0; i < 5; i++)
{
int x = TopK(&mh);
printf("%d ", x);
}
system("pause");
return 0;
}
寻找中位数 295
class MedianFinder {
priority_queue<int> lo; // max heap
priority_queue<int, vector<int>, greater<int>> hi; // min heap
public:
// Adds a number into the data structure.
void addNum(int num)
{
lo.push(num); // Add to max heap
hi.push(lo.top()); // balancing step
lo.pop();
if (lo.size() < hi.size()) {
// maintain size property
lo.push(hi.top());
hi.pop();
}
}
// Returns the median of current data stream
double findMedian()
{
return lo.size() > hi.size() ? (double) lo.top() : (lo.top() + hi.top()) * 0.5;
}
};