二、設計一個支持增量操作的棧(Weekly Contest 180)

題目描述:
請你設計一個支持下述操作的棧。

實現自定義棧類 CustomStack :

CustomStack(int maxSize):用 maxSize 初始化對象,maxSize 是棧中最多能容納的元素數量,棧在增長到 maxSize 之後則不支持 push 操作。
void push(int x):如果棧還未增長到 maxSize ,就將 x 添加到棧頂。
int pop():返回棧頂的值,或棧爲空時返回 -1 。
void inc(int k, int val):棧底的 k 個元素的值都增加 val 。如果棧中元素總數小於 k ,則棧中的所有元素都增加 val 。

示例:

輸入:
[“CustomStack”,“push”,“push”,“pop”,“push”,“push”,“push”,“increment”,“increment”,“pop”,“pop”,“pop”,“pop”]
[[3],[1],[2],[],[2],[3],[4],[5,100],[2,100],[],[],[],[]]
輸出:
[null,null,null,2,null,null,null,null,null,103,202,201,-1]
解釋:
CustomStack customStack = new CustomStack(3); // 棧是空的 []
customStack.push(1); // 棧變爲 [1]
customStack.push(2); // 棧變爲 [1, 2]
customStack.pop(); // 返回 2 --> 返回棧頂值 2,棧變爲 [1]
customStack.push(2); // 棧變爲 [1, 2]
customStack.push(3); // 棧變爲 [1, 2, 3]
customStack.push(4); // 棧仍然是 [1, 2, 3],不能添加其他元素使棧大小變爲 4
customStack.increment(5, 100); // 棧變爲 [101, 102, 103]
customStack.increment(2, 100); // 棧變爲 [201, 202, 103]
customStack.pop(); // 返回 103 --> 返回棧頂值 103,棧變爲 [201, 202]
customStack.pop(); // 返回 202 --> 返回棧頂值 202,棧變爲 [201]
customStack.pop(); // 返回 201 --> 返回棧頂值 201,棧變爲 []
customStack.pop(); // 返回 -1 --> 棧爲空,返回 -1

提示:

1 <= maxSize <= 1000
1 <= x <= 1000
1 <= k <= 1000
0 <= val <= 100
每種方法 increment,push 以及 pop 分別最多調用 1000 次
常規來就行

class CustomStack {
        private int[] datas;
        private int cur = 0;

        public CustomStack(int maxSize) {
            datas = new int[maxSize];
        }

        public void push(int x) {
            if (cur >= datas.length) {
                return;
            }

            datas[cur] = x;
            cur ++;
        }

        public int pop() {
            if (cur <= 0) {
                return -1;
            }

            cur --;
            return datas[cur];
        }

        public void increment(int k, int val) {
            int right = Math.min(k, cur);
            for (int i = 0; i < right; i ++) {
                datas[i] += val;
            }
        }
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章