forked from srishilesh/Data-Structure-and-Algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path1381_Design_stack_with_increment_operation
91 lines (82 loc) · 2.24 KB
/
1381_Design_stack_with_increment_operation
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
// https://leetcode.com/problems/design-a-stack-with-increment-operation/
class CustomStack {
int n;
int[] inc;
Stack<Integer> stack;
public CustomStack(int maxSize) {
n = maxSize;
inc = new int[n];
stack = new Stack<>();
}
public void push(int x) {
if (stack.size() < n)
stack.push(x);
}
public int pop() {
int i = stack.size() - 1;
if (i < 0)
return -1;
if (i > 0)
inc[i - 1] += inc[i];
int res = stack.pop() + inc[i];
inc[i] = 0;
System.out.println("POp()");
for (int j : inc)
System.out.print(j+ " ");
System.out.println();
return res;
}
public void increment(int k, int val) {
int i = Math.min(k, stack.size()) - 1;
if (i >= 0)
inc[i] += val;
System.out.println("Inc");
for (int j : inc)
System.out.print(j+ " ");
System.out.println();
}
}
// class CustomStack {
// int maxsize;
// Stack<Integer> stack;
// public CustomStack(int maxSize) {
// maxsize = maxSize;
// stack = new Stack<Integer>();
// }
// public void push(int x) {
// if (stack.size() < maxsize )
// stack.push(x);
// }
// public int pop() {
// if (!stack.isEmpty())
// return stack.pop();
// else
// return -1;
// }
// public void increment(int k, int val) {
// Stack<Integer> temp = new Stack<Integer>();
// if (stack.size() < k) {
// while (!stack.isEmpty()) {
// temp.push(stack.pop() +val);
// }
// }
// else {
// while (!stack.isEmpty()) {
// temp.push(stack.pop());
// }
// while (k-- > 0) {
// stack.push(temp.pop() + val);
// }
// }
// while (!temp.isEmpty()) {
// stack.push(temp.pop());
// }
// }
// }
// /**
// * 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);
// */