-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path155_MinStack
More file actions
90 lines (73 loc) · 1.92 KB
/
155_MinStack
File metadata and controls
90 lines (73 loc) · 1.92 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
Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.
push(x) -- Push element x onto stack.
pop() -- Removes the element on top of the stack.
top() -- Get the top element.
getMin() -- Retrieve the minimum element in the stack.
class MinStack {
List<Integer> list = new ArrayList<>();
int minValue = Integer.MAX_VALUE;
public void push(int x) {
list.add(x);
minValue = Math.min(minValue, x);
}
public void pop() {
if(list.size() > 1) {
if(list.get(list.size()-1) == minValue) {
list.remove(list.size()-1);
minValue = list.get(0);
for(int i = 0; i < list.size(); i++) {
minValue = Math.min(minValue, list.get(i));
}
}else{
list.remove(list.size()-1);
}
}else{
if(list.size() == 1) {
list.remove(list.size()-1);
minValue = Integer.MAX_VALUE;
}
}
}
public int top() {
if(list.size() >= 1) {
return list.get(list.size()-1);
}
return 0;
}
public int getMin() {
return minValue;
}
}
other's solution:
public class MinStack {
long min;
Stack<Long> stack;
public MinStack(){
stack=new Stack<>();
}
public void push(int x) {
if (stack.isEmpty()){
stack.push(0L);
min=x;
}else{
stack.push(x-min);//Could be negative if min value needs to change
if (x<min) min=x;
}
}
public void pop() {
if (stack.isEmpty()) return;
long pop=stack.pop();
if (pop<0) min=min-pop;//If negative, increase the min value
}
public int top() {
long top=stack.peek();
if (top>0){
return (int)(top+min);
}else{
return (int)(min);
}
}
public int getMin() {
return (int)min;
}
}