-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMinStack_155.java
More file actions
93 lines (83 loc) · 2.19 KB
/
Copy pathMinStack_155.java
File metadata and controls
93 lines (83 loc) · 2.19 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
package Stack_Queue;
import java.util.Deque;
import java.util.LinkedList;
import java.util.Stack;
/**
* 最小栈
*/
public class MinStack_155 {
/** initialize your data structure here.
* 空间为O(n)
*
private Stack<Integer> dataStack;
private Stack<Integer> minStack;
public MinStack_155() {
dataStack=new Stack<Integer>();
minStack=new Stack<Integer>();
}
public void push(int x) {
dataStack.push(x);
if(minStack.isEmpty()||x<(int)minStack.peek())
minStack.push(x);
else
minStack.push((int)minStack.peek());
}
public void pop() {
assert (!dataStack.isEmpty()&&!minStack.isEmpty());
dataStack.pop();
minStack.pop();
}
public int top() {
assert (!dataStack.isEmpty()&&!minStack.isEmpty());
return (int)dataStack.peek();
}
public int getMin() {
assert (!dataStack.isEmpty()&&!minStack.isEmpty());
return (int)minStack.peek();
}
*/
/**
* 空间为O(1)
* 存放与最小值的差值diff
* diff<0:表明元素比先前的最小值还要小,即元素为现在的最小值
* diff>0:表明元素比最小值大,最小值加差值即为所求元素
* 使用Long避免溢出
* */
private Deque<Long> stack;
private long minValue;
public MinStack_155() {
stack=new LinkedList<>();
minValue=0;
}
public void push(int x) {
if(stack.isEmpty()){
stack.push(0L);
minValue=x;
}else{
long diff=x-minValue;
stack.push(diff);
minValue=diff<0?x:minValue;
}
}
public void pop() {
if(!stack.isEmpty()){
long res;
long diff=stack.pop();
if(diff<0){
res=minValue;
minValue=res-diff;
}else{
res=minValue+diff;
}
}
}
public int top() {
assert(!stack.isEmpty());
long diff=stack.peek();
return (int)(diff>0?minValue+diff:minValue);
}
public int getMin() {
assert (!stack.isEmpty());
return (int)minValue;
}
}