Leetcode解题: Min stack (155)

Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.

1
2
3
4
5
6
7
8
9
10
11
12
13
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.
Example:
MinStack minStack = new MinStack();
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
minStack.getMin(); --> Returns -3.
minStack.pop();
minStack.top(); --> Returns 0.
minStack.getMin(); --> Returns -2.

解法1:

这题可以作为让你写一个Stack的class的follow up问题。
Implenment stack的时候可以用arraylist而不是用array, 这样就不用自己写一个resize function来维护底层数据的存放。
维护一个min, 可以有两个方法。一个是维护另一个arraylist, 保存对应每一个数据当前的最小值。
另一个方法是class MinStack extends Iterable, 然后需要有一个iterator(), 来返回一个Iterator的classmyiteraor,
这个myiterator implements Iterator 需要两个函数,hasNext()和next()

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
public class MinStack {
/** initialize your data structure here. */
List<Integer> data;
List<Integer> mins;
public MinStack() {
data = new ArrayList<Integer>();
mins = new ArrayList<Integer>();
}
public void push(int x) {
data.add(x);
if (mins.size() > 0) {
mins.add(mins.get(mins.size() - 1) < x ? mins.get(mins.size() - 1) : x);
} else {
mins.add(x);
}
}
public void pop() {
if (data.size() > 0) {
data.remove(data.size() - 1);
mins.remove(mins.size() - 1);
}
}
public int top() {
return data.get(data.size() - 1);
}
public int getMin() {
return mins.get(mins.size() - 1);
}
}
/**
* Your MinStack object will be instantiated and called as such:
* MinStack obj = new MinStack();
* obj.push(x);
* obj.pop();
* int param_3 = obj.top();
* int param_4 = obj.getMin();
*/