代码随想录1刷-day5,栈和队列

栈与队列

栈提供push 和 pop 等等接口,所有元素必须符合先进后出规则,所以栈不提供走访功能,也不提供迭代器(iterator)。 不像是set 或者map 提供迭代器iterator来遍历所有元素。
栈是以底层容器完成其所有的工作,对外提供统一的接口,底层容器是可插拔的(也就是说我们可以控制使用哪种容器来实现栈的功能)。
我们常用的SGI STL,如果没有指定底层实现的话,默认是以deque为缺省情况下栈的底层结构。
deque是一个双向队列,只要封住一段,只开通另一端就可以实现栈的逻辑了。
SGI STL中队列底层实现缺省情况也是使用deque实现的。
当然也可以指定底层实现:

std::stack<int, std::vector<int> > third;  // 使用vector为底层容器的栈

队列中先进先出的数据结构,同样不允许有遍历行为,不提供迭代器, SGI STL中队列一样是以deque为缺省情况下的底部结构。
当然同样可以指定底层实现:

std::queue<int, std::list<int>> third; // 定义以list为底层容器的队列

在c++中,栈和队列一般都不归类成容器,而是归类成container adapter( 容器适配器)

用栈实现队列:

    1. 用栈实现队列
class MyQueue {
public:
// 用两个栈实现队列
    stack<int> stIn;
    stack<int> stOut;
    MyQueue() {

    }
    
    void push(int x) {
        stIn.push(x);
    }
    
    int pop() {
        // 只当stOut为空时,才将stIn中的数转移到stOut
        if(stOut.empty())
        {
            while(!stIn.empty())
            {
                stOut.push(stIn.top());
                stIn.pop();
            }
        }
        int result = stOut.top();
        stOut.pop();
        return result;
    }
    
    int peek() {
        int res = this->pop();  // 直接复用已有的
        stOut.push(res);
        return res;
    }
    
    bool empty() {
        return stIn.empty()&&stOut.empty();
    }
};

/**
 * 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();
 */

用队列实现栈

  • 225 用队列实现栈
    这道题使用一个队列即可实现,但是在pop操作时需要先将前面n-1个数插到后面去,queue的常用操作有pop、push、front、back、empty等
class MyStack {
public:
    queue<int> que1;
    MyStack() {

    }
    
    void push(int x) {
        que1.push(x);
    }
    
    // pop的逻辑,先把队列头中的依次放到队列尾
    int pop() {
        for(int i=0;i<que1.size()-1;i++)
        {
            que1.push(que1.front());
            que1.pop();
        }
        int temp = que1.front();
        que1.pop();
        return temp;
    }
    
    int top() {
        return que1.back();
    }
    
    bool empty() {
        return que1.empty();
    }
};

/**
 * 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();
 */

有效的括号

    1. 有效的括号
class Solution {
public:
    bool isValid(string s) {
        if(s.size()%2)
            return false;
        stack<char> st;
        for(char& c:s)
        {
            if(c=='(')
                st.push(')');
            else if(c=='[')
                st.push(']');
            else if(c=='{')
                st.push('}');
            else if(!st.empty() && c==st.top()) // 注意st是空的话,st.top非法
                st.pop();
            else
                return false;
        }
        if(st.empty())
            return true;
        return false;
    }
};

删除字符串中相邻重复项

    1. 删除字符串中所有相邻的重复项
class Solution {
public:
    string removeDuplicates(string s) {
        stack<char> st;
        string result;
        for(char& c:s)
        {
            if(st.empty() || st.top()!=c)
                st.push(c);
            else
                st.pop();
        }
        while(!st.empty())
        {
            result+=st.top();
            // result=st.top()+result; // 这样的话开销很大
            st.pop();
        }

        reverse(result.begin(),result.end());
        return result;
    }
};

逆波兰表达式求值

    1. 逆波兰表达式求值
class Solution {
public:
    int evalRPN(vector<string>& tokens) {
        // 用栈处理,每次遇到数字就入栈,遇到运算符就出栈两个数字,运算结果再入栈
        stack<int> st;
        int temp1, temp2;
        for(int i=0; i<tokens.size(); i++)
        {
            if(tokens[i]=="+" || tokens[i]=="-" || tokens[i]=="*" || tokens[i]=="/")
            {
                temp1 = st.top();
                st.pop();
                temp2 = st.top();
                st.pop();
                if(tokens[i]=="+")  st.push(temp1+temp2);
                else if(tokens[i]=="-") st.push(temp2-temp1);       // 注意顺序
                else if(tokens[i]=="*") st.push(temp1*temp2);
                else st.push(temp2/temp1);      // 注意顺序
            }
            else 
                st.push(stoi(tokens[i]));
        }
        return st.top();
    }
};

滑动窗口的最大值(单调队列实现)

  • 239 滑动窗口最大值
// 时间复杂度O(n),空间复杂度O(k)
class Solution {
public:
    vector<int> maxSlidingWindow(vector<int>& nums, int k) {
        // 这道题用单调队列实现
        deque<int> que;     // queue底层默认也是使用的deque
        vector<int> result(nums.size()-k+1, 0);
        for(int i=0; i<nums.size(); i++)
        {
            while(!que.empty() && que.back()<nums[i])       // 维护单调的队列,这也是为什么要使用deque,而不使用queue
                que.pop_back();
            que.push_back(nums[i]);

            if(i>=k-1)  
            {
                result[i-k+1] = que.front();
                if(nums[i-k+1]==que.front())        // 说明这个最大值将被移出窗口
                    que.pop_front();
            }
        }
        return result;
    }
};

前k个高频元素(优先队列典型题)

    1. 前k个高频元素
      这种求前k个的问题用优先队列解决,求前k小的用大顶堆,求前K大的用小顶堆,定义方法是
      priority_queue<pair<int,int>, vector<pair<int,int>>, greater<pair<int,int>>> heap;
// 时间复杂度O(nlogk), 空间复杂度O(n)
#include <unordered_map>
class Solution {
public:
    vector<int> topKFrequent(vector<int>& nums, int k) {
        //先用哈希表存储,然后放到小顶堆里面,最后返回前k个
        priority_queue<pair<int,int>, vector<pair<int,int>>, greater<pair<int,int>>> heap;
        unordered_map<int,int> map;
        for(int& num:nums)
            map[num]++;
        // 建堆
        int cnt = 0;
        for(const auto& pair:map)
        {
            int key = pair.first;
            int value = pair.second;
            if(cnt<k)
                heap.push(make_pair(value, key));
            else
            {
                if(value>heap.top().first)
                {
                    heap.pop();
                    heap.push(make_pair(value, key));
                }
            }
            cnt++;
        }
        //返回前k个数
        vector<int> result(k);
        for(int i =k-1; i>=0; i--)
        {
            result[i] = (heap.top().second);
            heap.pop();
        }
        return result;
    }
};
  • 7
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值