-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQ1381DesignStack.java
More file actions
95 lines (79 loc) · 2.36 KB
/
Copy pathQ1381DesignStack.java
File metadata and controls
95 lines (79 loc) · 2.36 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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
/*
@b-knd (jingru) on 04 AUgust 2022 10:06:00
*/
//alternative, faster solution (lazy increment O(1))
class CustomStack {
Stack<Integer> stack = new Stack<>();
int[] inc;
int maxSize;
public CustomStack(int maxSize) {
inc = new int[maxSize];
this.maxSize = maxSize;
}
public void push(int x) {
if(stack.size() < maxSize){
stack.push(x);
}
}
public int pop() {
int i = stack.size()-1;
if(i < 0){
return -1;
} else if (i > 0){
inc[i-1] += inc[i];
}
int res = stack.pop()+inc[i];
inc[i] = 0;
return res;
}
public void increment(int k, int val) {
int i = Math.min(k, stack.size())-1;
//last index where increment takes place
if(i >= 0){
inc[i] += val;
}
}
}
//Runtime: 5 ms, faster than 95.16% of Java online submissions for Design a Stack With Increment Operation.
//Memory Usage: 43.3 MB, less than 88.53% of Java online submissions for Design a Stack With Increment Operation.
/*---------------------------------------------------------------------------------------------------------------*/
//my submission
class CustomStack {
Stack<Integer> stack = new Stack<>();
Stack<Integer> temp = new Stack<>();
int maxSize;
public CustomStack(int maxSize) {
this.maxSize = maxSize;
}
public void push(int x) {
if(stack.size() < maxSize){
stack.push(x);
}
}
public int pop() {
if(stack.empty()){
return -1;
}
return stack.pop();
}
public void increment(int k, int val) {
while(!stack.empty()){
temp.push(stack.pop());
}
while(stack.size() < k && !temp.empty()){
stack.push(temp.pop()+val);
}
while(!temp.empty()){
stack.push(temp.pop());
}
}
}
//Runtime: 277 ms, faster than 5.06% of Java online submissions for Design a Stack With Increment Operation.
//Memory Usage: 55.2 MB, less than 12.81% of Java online submissions for Design a Stack With Increment Operation.
/**
* 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);
*/