zoukankan      html  css  js  c++  java
  • 牛客网剑指offer栈和队列题目总结(共10道)

    栈和队列

    1、用两个栈实现队列(剑指5)

    用两个栈来实现一个队列,完成队列的Push和Pop操作。队列中的元素为int类型。

    class Solution
    {
    public:
        void push(int node) {
            while(!stack2.empty()){
                stack1.push(stack2.top());
                stack2.pop();
            }
            stack1.push(node);
        }
    
        int pop() {
            while(!stack1.empty()){
                stack2.push(stack1.top());
                stack1.pop();
            }
            int t=stack2.top();
            stack2.pop();
            return t;
        }
    
    private:
        stack<int> stack1;
        stack<int> stack2;
    };
    

    2、包含min函数的栈(剑指20)

    定义栈的数据结构,请在该类型中实现一个能够得到栈中所含最小元素的min函数(时间复杂度应为O(1))。

    注意:保证测试中不会当栈为空的时候,对栈调用pop()或者min()或者top()方法。

    class Solution {
    public:
        void push(int value) {
            if(s2.empty()||value<=s2.top()) s2.push(value);
            s1.push(value);
        }
        void pop() {
            if(s1.top()==s2.top()) s2.pop();
            s1.pop();
        }
        int top() {
            return s1.top();
        }
        int min() {
            return s2.top();
        }
        stack <int> s1;
        stack <int> s2;
    };
    

    3、栈的压入、弹出序列(剑指21)

    输入两个整数序列,第一个序列表示栈的压入顺序,请判断第二个序列是否可能为该栈的弹出顺序。假设压入栈的所有数字均不相等。例如序列1,2,3,4,5是某栈的压入顺序,序列4,5,3,2,1是该压栈序列对应的一个弹出序列,但4,3,5,1,2就不可能是该压栈序列的弹出序列。(注意:这两个序列的长度是相等的)

    class Solution {
    public:
        bool IsPopOrder(vector<int> pushV,vector<int> popV) {
            if(pushV.size()==0||pushV.size()!=popV.size()) return false;
            vector<int> temp;
            for(int i=0,j=0;i<pushV.size();i++){
                temp.push_back(pushV[i]);
                while(j<popV.size()&&temp.back()==popV[j]){
                    temp.pop_back();
                    j++;
                }
            }
            return temp.empty();
        }
    };
    
  • 相关阅读:
    动态规划——Best Time to Buy and Sell Stock IV
    动态规划——Split Array Largest Sum
    动态规划——Burst Ballons
    动态规划——Best Time to Buy and Sell Stock III
    动态规划——Edit Distance
    动态规划——Longest Valid Parentheses
    动态规划——Valid Permutations for DI Sequence
    构建之法阅读笔记05
    构建之法阅读笔记04
    构建之法阅读笔记03
  • 原文地址:https://www.cnblogs.com/yjcoding/p/13217034.html
Copyright © 2011-2022 走看看