题目:
设计包含
min 函数的栈。
定义栈的数据结构,要求添加一个 min函数,能够得到栈的最小元素。要求函数
min、push以及
pop的时间复杂度都是
O(1)。
解题思路:
栈是后进先出的数据结构,要求查询得到栈的最小元素,我们内部实现可以设计两个栈A、B,A栈保存用户进栈数据,B栈保存当前A栈中最小元素。但用户数据进栈,判断B栈的top元素,如果小于用户数据,则B栈top元素再次进入B栈,否则用户数据进入B栈。A栈与B栈一一对应,B栈index索引标志A栈index索引时的最小数据。
由此思路,我们封装一个MinEntry,用于保存当前用户数据,和当前栈的最小值。
代码实现:
public class MinStack {
private List<MinEntry> stack = null;
public MinStack(){
stack = new ArrayList<MinEntry>();
}
public MinStack(int size){
stack = new ArrayList<MinEntry>();
}
public void push(Integer value){
Integer minest = value;
if (stack.size() > 0){
MinEntry top = stack.get(stack.size() - 1);
if (top.minest < minest){
minest = top.minest;
}
}
stack.add(new MinEntry(value, minest));
}
public MinEntry pop(){
int n = stack.size();
if (n <= 0){
throw new EmptyStackException();
}
return stack.remove(n - 1);
}
public MinEntry peek(){
int n = stack.size();
if (n <= 0){
throw new EmptyStackException();
}
return stack.get(n - 1);
}
public boolean empty(){
return stack.isEmpty();
}
class MinEntry{
private Integer value;
private Integer minest;
public MinEntry(Integer value, Integer minest){
this.value = value;
this.minest = minest;
}
public Integer getValue(){
return this.value;
}
public Integer getMinest(){
return minest;
}
}
}
Junit代码如下:
public class MinStackTest {
@Test
public void testPop() {
int count = 100000;
Random random = new Random();
List<Integer> minList = new ArrayList<Integer>(count);
MinStack stack = new MinStack(count);
Integer minest = null;
for (int i = 0; i < count; i++){
Integer value = random.nextInt();
if (minest == null || value < minest){
minest = value;
}
minList.add(minest);
stack.push(value);
}
Collections.sort(minList);
for (int i = 0; i < count; i++){
assertEquals(stack.pop().getMinest(), minList.get(i));
}
}