Question:How would you design a stack which, in addition to push and pop, also has functions which return the minimum and maximum elements? Push, pop, min, max should all operate inO(1) time.
思路:1.用两个数组存最大值和最小值下标序列。保证max和min操作时间复杂度为0(1)。
2.每次push时,如果push值比当前最大值大,则更新最大值下标数组,该数组在该push值的下标位置处值为当前最大值(即指向前一个最大值),随后用push值更新最大值。否则将最大值下标数组在该push值的下标位置处赋值-1;同理更新最小值。
3.每次pop时,如果pop的值正好是当前最大值,则通过最大值下标数组找到当前最大值前一个最大值(即pop当前最大值后的最大值)。同理更新最小值。
package CareerCup;
public class MinMaxStack
{
public static int MAX = 10;
private int stackItem[];
private int link2NextMaxItem[];
private int link2NextMinItem[];
private int top;
private int maxIndex;
private int minIndex;
public static void main(String[] args) throws Exception
{
MinMaxStack ss = new MinMaxStack();
ss.print();
for(int i=0;i<MAX;i++)
{
System.out.println("Push "+i+":");
ss.push(i);
ss.print();
}
ss.print();
for(int i=0;i<MAX/2;i++)
{
System.out.println("Pop "+i+":");
ss.pop();
ss.print();
}
ss.print();
}
public MinMaxStack()
{
stackItem = new int[MAX];
link2NextMaxItem = new int[MAX];
link2NextMinItem = new int[MAX];
top = -1;
maxIndex = -1;
minIndex = -1;
}
public void push(int data) throws Exception
{
top++;
if(top >= MAX)
throw new Exception("The stack is full!");
else
{
stackItem[top] = data;
if(data > max())
{
link2NextMaxItem[top] = maxIndex;
maxIndex = top;
}
else
{
link2NextMaxItem[top] = -1;
}
if(data < min())
{
link2NextMinItem[top] = minIndex;
minIndex = top;
}
else
{
link2NextMinItem[top] = -1;
}
}
}
public int pop() throws Exception
{
int res=0;
if(top < 0)
throw new Exception("The stack is empty!");
else
{
res = stackItem[top];
if(top == maxIndex)
maxIndex = link2NextMaxItem[top];
if(top == minIndex)
minIndex = link2NextMinItem[top];
top--;
}
return res;
}
public int max()
{
if(maxIndex >=0)
return stackItem[maxIndex];
else
return Integer.MIN_VALUE;
}
public int min()
{
if(minIndex >=0)
return stackItem[minIndex];
else
return Integer.MAX_VALUE;
}
public void print()
{
System.out.print("The stack is:{");
for(int i=0;i<=top;i++)
System.out.print(stackItem[i]+",");
System.out.print("}");
System.out.println();
System.out.println("The max item is:"+max());
System.out.println("The min item is:"+min());
}
}