[LeetCode 周赛180] 2. 设计一个支持增量操作的栈(模拟、暴力、代码优化)

1. 题目来源

链接:1381. 设计一个支持增量操作的栈

2. 题目说明

在这里插入图片描述

3. 题目解析

方法一:模拟+暴力+常规解法

题意很明确,模拟即可,主要思路如下:

  • 这是个有固定容量初始化的栈,所以我们需要创建一个变量来记录这个 capacity
  • 由于是要将栈底的 k 个元素进行加 val 的操作,那么很容易想到拿另外一个栈转接一下就可以了,当然采用数组也是完全在进行从后往前的输出也是完全 ok
  • 首先将 s1 的数据全部倒给 s2
  • 再将 s2 顺序出栈,其前 k 个给他加上 val,后面的所有数据原封不动倒进 s1 即可

参见代码如下:

// 执行用时 :80 ms, 在所有 C++ 提交中击败了100.00%的用户
// 内存消耗 :28.6 MB, 在所有 C++ 提交中击败了100.00%的用户

class CustomStack {
public:
    CustomStack(int maxSize) {
        size = maxSize;
    }
    
    void push(int x) {
        if (s1.size() < size) s1.push(x);
    }
    
    int pop() {
        int tmp = -1;
        if (!s1.empty()) {
            tmp = s1.top();
            s1.pop();
        }
        return tmp;
    }
    
    void increment(int k, int val) {
        while (!s1.empty()) {
            int tmp = s1.top();
            s2.push(tmp);
            s1.pop();
        }
        int cnt = k;
        while (!s2.empty()) {
            if (cnt) {
                int tmp = s2.top() + val;
                s1.push(tmp);
                s2.pop();
                --cnt;
            }
            if (cnt == 0 and !s2.empty()) {
                int tmp = s2.top();
                s1.push(tmp);
                s2.pop();
            }
        }
    }
    
private:
    stack<int> s1;
    stack<int> s2;
    int size = 0;
};

/**
 * Your CustomStack object will be instantiated and called as such:
 * CustomStack* obj = new CustomStack(maxSize);
 * obj->push(x);
 * int param_2 = obj->pop();
 * obj->increment(k,val);
 */

方法二:模拟+暴力+代码优化+常规解法

思路同方法一,写法做优化。采用顺序表数组结构 increment 部分作优化。

参见代码如下:

// 执行用时 :32 ms, 在所有 C++ 提交中击败了100.00%的用户
// 内存消耗 :19.8 MB, 在所有 C++ 提交中击败了100.00%的用户

class CustomStack {
public:
    int curSize, maxSize;
    int stack[1050];
    
    CustomStack(int maxSize) {
        curSize = 0;
        this->maxSize = maxSize;
    }
    
    void push(int x) {
        if (curSize >= maxSize) return;
        stack[++curSize] = x;
    }
    
    int pop() {
        if (curSize == 0) return -1;
        int ret = stack[curSize--];
        return ret;
    }
    
    void increment(int k, int val) {
        for (int i = 1; i <= k && i <= curSize; i++)
            stack[i] += val;
    }
};

/**
 * Your CustomStack object will be instantiated and called as such:
 * CustomStack* obj = new CustomStack(maxSize);
 * obj->push(x);
 * int param_2 = obj->pop();
 * obj->increment(k,val);
 */
发布了359 篇原创文章 · 获赞 259 · 访问量 7万+

猜你喜欢

转载自blog.csdn.net/yl_puyu/article/details/104908102