leetcode--栈和队列

来源:互联网 发布:国外油画网站知乎 编辑:程序博客网 时间:2024/06/11 21:01

基本操作:

STL stack

#include <stack>
S.top():取出栈顶
S.empty():判断栈是否为空
S.push(x):将x压入栈中
S.pop():弹出栈顶
S.size():栈的存储元素个数

STL queue

#include <queue>
Q.empty():判断队列是否为空
Q.front():返回队列的头部元素
Q.back():返回队列的尾部元素
Q.pop():弹出队列头部元素
Q.push(x):将x添加至队列
Q.size():返回队列中的存储元素个数

leetcode题目

225. Implement Stack using Queues

题意:

使用队列实现栈

解题思路:

Stack和Queue之间只有push(x)方法不同,一个是放到头处,一个放到尾处,可以做一个临时队列,先压入心节点,再顺利压入原队列元素,再按顺序压回原队列中。

代码:

    MyStack() {    }    /** Push element x onto stack. */    void push(int x) {        std::queue<int> temp_queue;        temp_queue.push(x);        while(!_data.empty()){            temp_queue.push(_data.front());            _data.pop();        }        while(!temp_queue.empty()){            _data.push(temp_queue.front());            temp_queue.pop();        }    }    /** Removes the element on top of the stack and returns that element. */    int pop() {        int x=_data.front();        _data.pop();        return x;    }    /** Get the top element. */    int top() {        return _data.front();    }    /** Returns whether the stack is empty. */    bool empty() {        return _data.empty();    }private:    std::queue<int> _data;

232. Implement Queue using Stacks

题意:

使用栈实现队列

解题思路:

同理,栈和队列中只有push(x)的方法不同,从一个栈中出来再放到另一个栈会导致顺序改变,设一个临时的栈,从原栈中出压进临时栈,然后压入x,在放回到原栈中。

代码:

MyQueue() {    }    /** Push element x to the back of queue. */    void push(int x) {        std::stack<int> temp_stack;        while(!_data.empty()){            temp_stack.push(_data.top());            _data.pop();        }        temp_stack.push(x);        while(!temp_stack.empty()){            _data.push(temp_stack.top());            temp_stack.pop();        }    }    /** Removes the element from in front of queue and returns that element. */    int pop() {        int x=_data.top();        _data.pop();        return x;    }    /** Get the front element. */    int peek() {        return _data.top();    }    /** Returns whether the queue is empty. */    bool empty() {        return _data.empty();    }private:    std::stack<int> _data;};

155. Min Stack

题意:

实现一个可以返回栈的最小值的栈

解题思路:

在数据结构中定义一个记录每个状态的最小值的堆栈。

代码:

class MinStack {public:    /** initialize your data structure here. */   MinStack(){    }    void push(int x){        _data.push(x);        if(_min.empty()){            _min.push(x);        }        else{            if(x>_min.top()){                x=_min.top();            }            _min.push(x);        }    }    void pop(){        _data.pop();        _min.pop();    }    int top(){        return _data.top();    }    int getMin(){        return _min.top();    }private:    std::stack<int> _data;    std::stack<int> _min;};

224. Basic Calculator

题意:

实现一个基础的计算器,实现加减运算,运算符包括+-(),表达式中可能会有空格,空格不会影响结果。

解题思路:

用有限状态自动机实现字符的读取,能省去很多if else的判断语句。
状态BEGIN \ NUMBER \ OPERATOR
BEGIN:数字转去NUMBER状态,操作符转去OPERATOR状态,并进行退格操作。
NUMBER:数字的话继续执行NUMBER状态,number=number+s[i]*10,若是操作符,执行运算操作,转向OPERATOR状态并执行退格操作。
OPERATOR:遇到数字退格转向NUMBER状态,遇到字符分情况讨论,用一个compute_flag实现()的功能。

代码:

class Solution {public: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);    }    if(operation_stack.top()=='-'){        number_stack.push(num1-num2);    }    operation_stack.pop();}    int calculate(string s) {    static const int STATE_BEGIN=0;    static const int NUMBER_STATE=1;    static const int OPERATION_STATE=2;    std::stack<int> number_stack;    std::stack<char> operation_stack;    int number=0;    int STATE=STATE_BEGIN;    int compute_flag=0;    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=NUMBER_STATE;                }                else{ STATE=OPERATION_STATE;}                i--;                break;            case NUMBER_STATE:                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=OPERATION_STATE;                }                break;            case OPERATION_STATE:                if(s[i]=='+'||s[i]=='-'){                    operation_stack.push(s[i]);                    compute_flag=1;                }                else if(s[i]=='('){                    STATE=NUMBER_STATE;                    compute_flag=0;                }                else if(s[i]>='0'&&s[i]<='9'){                    STATE=NUMBER_STATE;                    i--;                }                else if(s[i]==')'){                    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 0;    }    return number_stack.top();}};

215. Kth Largest Element in an Array

题意:

找出一个int的vector中第K大的数

解题思路:

可以读入全部数据,进行sort排序,时间复杂度是NlogN
运用最小堆的思想,维护一个K个数的最小堆,比堆顶大的话就压入。时间复杂度NlogK
最小堆和最大堆的定义:
std::priority queue<int> big_heap;默认构建最小堆
std::priority queue<int,std::vector<int>,std::greater<int>> small_heap;构建最大堆

代码:

class Solution {public:    int findKthLargest(vector<int>& nums, int k) {        std::priority_queue<int,std::vector<int>,std::greater<int>> Q;    for(int i=0;i<nums.size();i++){        if(Q.size()<k){            Q.push(nums[i]);        }        else if(Q.top()<nums[i]){            Q.pop();            Q.push(nums[i]);        }    }    return Q.top();    }};