-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathStackWithFindMin.java
74 lines (67 loc) · 1.44 KB
/
StackWithFindMin.java
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
/*https://practice.geeksforgeeks.org/problems/special-stack/1*/
/*https://leetcode.com/problems/min-stack/*/
class GfG{
public void push(int a,Stack<Integer> s)
{
//add code here.
s.push(a);
}
public int pop(Stack<Integer> s)
{
//add code here.
if (s.isEmpty()) return -1;
return s.pop();
}
public int min(Stack<Integer> s)
{
//add code here.
int min = Integer.MAX_VALUE;
if (s.isEmpty()) return -1;
for (int i = 0; i < s.size(); ++i)
if (s.get(i) < min)
min = s.get(i);
return min;
}
public boolean isFull(Stack<Integer>s, int n)
{
//add code here.
return s.size() == n;
}
public boolean isEmpty(Stack<Integer>s)
{
//add code here.
return s.isEmpty();
}
}
class MinStack {
int[] stack, minElem;
int top;
public MinStack() {
stack = new int[30000];
minElem = new int[30000];
top = -1;
}
public void push(int val) {
if (top == -1)
{
++top;
stack[top] = val;
minElem[top] = val;
}
else
{
++top;
stack[top] = val;
minElem[top] = Math.min(stack[top],minElem[top-1]);
}
}
public void pop() {
--top;
}
public int top() {
return stack[top];
}
public int getMin() {
return minElem[top];
}
}