-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path1381+Design a Stack With Increment Operation.cpp
More file actions
72 lines (55 loc) · 1.41 KB
/
1381+Design a Stack With Increment Operation.cpp
File metadata and controls
72 lines (55 loc) · 1.41 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
class CustomStack {
public:
CustomStack(int maxSize) : mMaxSize(maxSize) {
}
void push(int x) {
if (mVec.size() < mMaxSize) {
mVec.push_back(x);
}
}
int pop() {
if (mVec.size() == 0) return -1;
int num = mVec.back(); mVec.erase((--mVec.end()));
return num;
}
void increment(int k, int val) {
for (int i = 0; i < min(k, (int)mVec.size()); ++i)
mVec[i] += val;
}
private:
int mMaxSize;
vector<int> mVec;
};
class CustomStack {
public:
CustomStack(int maxSize) : mMaxSize(maxSize) {
mVec.resize(maxSize);
mInc.resize(maxSize);
top = -1;
}
void push(int x) {
if (top < mMaxSize - 1) {
++top;
mVec[top] = x;
}
}
int pop() {
if (top == -1) return -1;
int num = mVec[top] + mInc[top];
if (top > 0) {
mInc[top - 1] += mInc[top];
}
mInc[top] = 0;
--top;
return num;
}
void increment(int k, int val) {
int idx = min(k - 1, top);
if (idx >= 0) // top 可能是 -1
mInc[idx] += val;
}
private:
int mMaxSize;
int top; // 表示栈顶
vector<int> mVec, mInc; //mInc[i] 表示下标<=i的元素的增量
};