-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathDesignAStackWithIncrementOperation.java
61 lines (54 loc) · 1.51 KB
/
DesignAStackWithIncrementOperation.java
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
package io.ziheng.stack.leetcode;
import java.util.Deque;
import java.util.LinkedList;
/**
* LeetCode 1381. Design a Stack With Increment Operation
* https://leetcode.com/problems/design-a-stack-with-increment-operation/
*/
public class DesignAStackWithIncrementOperation {
private int maxSize;
private int currentSize;
private Deque<Integer> primaryStack;
private Deque<Integer> secondaryStack;
public DesignAStackWithIncrementOperation(int maxSize) {
this.maxSize = maxSize;
this.currentSize = 0;
this.primaryStack = new LinkedList<>();
this.secondaryStack = new LinkedList<>();
}
public void push(int x) {
if (currentSize < maxSize) {
primaryStack.push(x);
currentSize++;
}
}
public int pop() {
if (currentSize != 0) {
currentSize--;
return primaryStack.pop();
} else {
return -1;
}
}
public void increment(int k, int val) {
/**
* currentSize = 5
* k = 2
* 0 -> 3 = 3
* 0 -> 2 = 2
*/
if (k > currentSize) {
k = currentSize;
}
for (int i = 0; i < currentSize - k; i++) {
secondaryStack.push(primaryStack.pop());
}
for (int i = 0; i < k; i++) {
secondaryStack.push(val + primaryStack.pop());
}
while (!secondaryStack.isEmpty()) {
primaryStack.push(secondaryStack.pop());
}
}
}
/* EOF */