-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMinStack2.java
More file actions
46 lines (39 loc) · 1.09 KB
/
MinStack2.java
File metadata and controls
46 lines (39 loc) · 1.09 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
import java.util.ArrayList;
import java.util.List;
/**
* Created by yasin_000 on 22.8.2017.
*/
public class MinStack2 {
List<Integer> records;
List<Integer> mins;
MinStack2(){
records = new ArrayList<>();
mins = new ArrayList<>();
}
public void push(int x){
records.add(x);
if (mins.isEmpty() || x <= mins.get(mins.size() - 1))
mins.add(x);
}
public int pop(){
if (records.isEmpty())
throw new IllegalStateException("Stack is empty");
int top = records.remove(size() - 1);
if (!mins.isEmpty() && top == mins.get(mins.size() - 1))
mins.remove(mins.size() - 1);
return top;
}
public int peek(){
if (records.isEmpty())
throw new IllegalStateException("Stack is empty");
return records.get(size() - 1) ;
}
public int getMin(){
if (!records.isEmpty())
return mins.get(mins.size() - 1);
return -1;
}
public int size(){
return records.size();
}
}