思路:
要求O(1)複雜度找到,不遍歷整個集合是不可能的。
但如果犧牲空間複雜度來滿足這個要求 也是可以的。
有兩種思路:
- 用兩個棧。一個存儲元素本身,一個存儲當前最小的元素。那麼入棧就得兩個都入,出棧也是。
- 用一個棧,但是存兩倍個數的元素。第一層存元素本身,第二層存當前最小值,入棧入兩次,第二次判斷最小元素並存入。出棧也是。
接下來就只看第二種方法的代碼:
class MinStack {
public static Stack<Integer> st;
/** initialize your data structure here. */
public MinStack() {
st = new Stack<Integer>();
}
public void push(int x) {
//空棧直接入棧
if(st.isEmpty()){
st.push(x);
st.push(x);
}else{
int tmp = st.peek();
st.push(x);
//獲取當前最小值,存入
if(tmp<=x){
st.push(tmp);
}else{
st.push(x);
}
}
}
public void pop() {
st.pop();
st.pop();
}
public int top() {
int tmp = st.pop();
int res = st.peek();
st.add(tmp);
return res;
}
public int getMin() {
return st.peek();
}
}