去面試微信實習,遇到這道算法題,當時被卡住,故今天把它寫出來做下知識整理,
原題:實現一個棧,滿足min() pop() push()方法的時間復雜度都為O(1).( min()返回棧中最小元素 )
思路1:用一個變量minItem記錄棧中的最小值,在push()中 每次加入一個item就跟minItem對比,item更小,只item賦給minItem,然后再min() 中直接return minItem;
這種思路沒考慮在pop()過程中,對minItem的影響,當棧頂元素是minItem,執行pop() 后minItem就不知道指向誰了,因為棧只記錄最小值而起,至於最小值之前那些大小關系都沒記錄
正確思路:為了實現更低的時間復雜度,我們都會想到用空間去換時間,所有這里增加一個數組來nextMinItem[index] 元素大小關系。如果當前最小值是 對象 item1 當push進來的item2比 item1更小,且元素個數從原本的a增加到a+1 這時候我們用我們就應該把item2這個更小的item賦給minItem 然后用nextMinItem[a+1] = item1 來記錄 item2 后面的次小值,這樣一來當item2 這個棧頂被pop()掉的話,我們就可以minItem = nextMinItem[a+1],來恢復minItem。
package 騰訊面試題;
public class Stack {
private int itemCount = 0;
private Item minItem = null;
private Item[] nextMinItem;
private Item stackTop = null;
private int maxSize = 100;
public Stack() {
nextMinItem = new Item[maxSize];
}
class Item {
int Data;
Item nextItem;
public Item(int data) {
this.Data = data;
}
}
public boolean push(Item item) {
if (itemCount == maxSize) {
System.out.println("棧已滿");
return false;
}
itemCount++;
if (minItem == null) {
minItem = item;
} else {
if (item.Data < minItem.Data) {
nextMinItem[itemCount] = minItem;
minItem = item;
}
}
item.nextItem = stackTop;
stackTop = item;
return true;
}
public boolean pop() {
if (itemCount == 0) {
System.out.println("棧是空的,無法出棧");
return false;
}
if (stackTop == minItem) {
minItem = nextMinItem[itemCount];
}
stackTop = stackTop.nextItem;
itemCount--;
return true;
}
public Item min() {
if (itemCount == 0) {
System.out.println("棧是空的,無最小值");
return null;
}
return minItem;
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Stack stack = new Stack();
stack.push(stack.new Item(5));
System.out.println("push:min=" + stack.min().Data+" itemCount="+stack.itemCount);
stack.push(stack.new Item(4));
System.out.println("push:min=" + stack.min().Data+" itemCount="+stack.itemCount);
stack.push(stack.new Item(3));
System.out.println("push:min=" + stack.min().Data+" itemCount="+stack.itemCount);
stack.push(stack.new Item(2));
System.out.println("push:min=" + stack.min().Data+" itemCount="+stack.itemCount);
stack.push(stack.new Item(1));
System.out.println("push:min=" + stack.min().Data+" itemCount="+stack.itemCount);
stack.pop();
System.out.println("pop :min=" + stack.min().Data+" itemCount="+stack.itemCount);
stack.pop();
System.out.println("pop :min=" + stack.min().Data+" itemCount="+stack.itemCount);
stack.pop();
System.out.println("pop :min=" + stack.min().Data+" itemCount="+stack.itemCount);
stack.pop();
System.out.println("pop :min=" + stack.min().Data+" itemCount="+stack.itemCount);
stack.pop();
System.out.println("棧結構為:\n|____1_____|\n|____2_____|\n|____3_____|\n|____4_____|\n|____5_____|\n");
}
}
運行結果:
