基本思想:
// 借助一个辅助栈,入栈时,若新元素比辅助栈栈顶元素小,则直接放入辅助站
//
反之,辅助站中放入次小元素(即辅助栈栈顶元素)====保证最小元素出栈时,次小元素被保存
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 |
static class MyStack { Integer[] value = new
Integer[ 10 ]; int
index = 0 ; MyStack miniStack; // 辅助栈 void
push(Integer vInteger) { this .push(vInteger); // 辅助栈中无元素或栈顶元素比新插入元素大 if
(miniStack.size() == 0
|| miniStack.peek() > vInteger) { miniStack.push(vInteger); } else
{ // 新插入元素较小 miniStack.push(miniStack.peek()); } } Integer peek() { return
miniStack.pop(); } // 出栈时,主栈与辅助栈一同弹出元素 Integer pop() { miniStack.pop(); return
value[index]; } Integer mini() { return
miniStack.pop(); } Integer size() { return
index; } } |
自定义栈类型,具有找到站内最小元素的min函数 ,且min(),pop(),push()函数的时间复杂度为O(1),布布扣,bubuko.com
自定义栈类型,具有找到站内最小元素的min函数 ,且min(),pop(),push()函数的时间复杂度为O(1)
原文:http://www.cnblogs.com/cugb-2013/p/3634528.html