-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLC1381.java
More file actions
74 lines (65 loc) · 1.53 KB
/
LC1381.java
File metadata and controls
74 lines (65 loc) · 1.53 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
73
74
/*
* LC1381
*/
class CustomStack {
int stack[];
int operations[];
int capacity;
int size;
int index;
public CustomStack(int maxSize) {
stack = new int[maxSize];
operations = new int[maxSize];
capacity = maxSize;
size = 0;
index = -1;
}
public void push(int x) {
if (isFull()) {
return;
}
index++;
size++;
stack[index] = x;
}
public int pop() {
if (isEmpty()) {
return -1;
}
int value = stack[index];
value += operations[index];
// ? This will also perform in the constant time
if (index > 0) {
operations[index - 1] += operations[index];
}
operations[index] = 0;
index--;
size--;
return value;
}
public void increment(int k, int val) {
if (isEmpty()) {
return;
}
int num = Math.min(size, k);
// ? This is helpful technique to do in a constant time
operations[num - 1] += val;
// ? This will not perform in a constant time
// for (int i = 0; i < num; i++) {
// stack[i] += val;
// }
}
private boolean isFull() {
return (size == capacity);
}
private boolean isEmpty() {
return (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);
*/