LeetCode #716 - Max Stack

本文介绍了一种名为MaxStack的数据结构设计,支持push、pop、top、peekMax和popMax操作。通过双栈实现,其中一个栈保持所有元素的压栈顺序,另一个栈保持栈顶为最大元素,确保了在O(1)时间内完成peekMax和popMax操作。

题目描述:

Design a max stack that supports push, pop, top, peekMax and popMax.

1. push(x) -- Push element x onto stack.

2. pop() -- Remove the element on top of the stack and return it.

3. top() -- Get the element on the top.

4. peekMax() -- Retrieve the maximum element in the stack.

5. popMax() -- Retrieve the maximum element in the stack, and remove it. If you find more than one maximum elements, only remove the top-most one.

Example 1:

MaxStack stack = new MaxStack();

stack.push(5); 

stack.push(1);

stack.push(5);

stack.top(); -> 5

stack.popMax(); -> 5

stack.top(); -> 1

stack.peekMax(); -> 5

stack.pop(); -> 1

stack.top(); -> 5

Note:

1. -1e7 <= x <= 1e7

2. Number of operations won't exceed 10000.

3. The last four operations won't be called when stack is empty.

class MaxStack {
public:
    /** initialize your data structure here. */
    MaxStack() {}
    
    void push(int x) {
        if(s1.empty()) s1.push(x);
        else s1.push(max(s1.top(),x));
        s2.push(x);
    }
    
    int pop() {
        int x=s2.top();
        s1.pop();
        s2.pop();
        return x;
    }
    
    int top() {
        return s2.top();
    }
    
    int peekMax() {
        return s1.top();
    }
    
    int popMax() {
        int x=s1.top();
        stack<int> temp;
        while(!s2.empty()&&s1.top()!=s2.top())
        {
            temp.push(s2.top());
            s1.pop();
            s2.pop();
        }
        s1.pop();
        s2.pop();
        while(!temp.empty()) 
        {
            push(temp.top());
            temp.pop();
        }
        return x;
    }
    
private:
    stack<int> s1; //保持栈顶为最大元素
    stack<int> s2; //按照压栈顺序保持所有元素
};

 

LeetCode 题目 491 - 递增子序列 (Incremental Subsequence) 是一道关于算法设计的中等难度题目。这道题要求你在给定整数数组 nums 中找出所有长度大于等于 1 的递增子序列。递增子序列是指数组中的一串连续元素,它们按照顺序严格增大。 解决这个问题的一个常见策略是使用动态规划(Dynamic Programming),特别是哈希表或者单调栈(Monotonic Stack)。你可以维护一个栈,每当遍历到一个比栈顶元素大的数字时,就将它推入栈,并更新当前最长递增子序列的长度。同时,如果遇到一个不大于栈顶元素的数字,就从栈顶开始检查是否存在更长的递增子序列。 以下是 C++ 解决此问题的一种简单实现: ```cpp class Solution { public: vector<int> lengthOfLIS(vector<int>& nums) { int n = nums.size(); if (n == 0) return {}; // 使用单调栈存储当前已知的最大子序列 stack<pair<int, int>> stk; stk.push({nums[0], 1}); for (int i = 1; i < n; ++i) { while (!stk.empty() && nums[i] > stk.top().first) { // 如果新数大于栈顶元素,找到一个更长的递增子序列 int len = stk.top().second + 1; ans.push_back(len); stk.pop(); } // 如果新数不大于栈顶元素,尝试从当前位置开始寻找更长子序列 if (!stk.empty()) { stk.top().second = max(stk.top().second, 1); } else { stk.push({nums[i], 1}); } } return ans; } private: vector<int> ans; }; ``` 在这个解决方案中,`ans` 存储所有的递增子序列长度,最后返回这个结果向量即可。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值