定義堆疊的資料結構,請在該型別中實作一個能夠得到堆疊的最小元素的 min 函式在該堆疊中,呼叫 min、push 及 pop 的時間復雜度都是 O(1),
示例:
MinStack minStack = new MinStack();
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
minStack.min(); --> 回傳 -3.
minStack.pop();
minStack.top(); --> 回傳 0.
minStack.min(); --> 回傳 -2.
來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/bao-han-minhan-shu-de-zhan-lcof
著作權歸領扣網路所有,商業轉載請聯系官方授權,非商業轉載請注明出處,
class MinStack {
Stack<Integer> stack1;
Stack<Integer> stack2;
/** initialize your data structure here. */
public MinStack() {
stack1=new Stack<Integer>();
stack2=new Stack<Integer>();
}
public void push(int x) {
stack1.add(x);
if(stack2.empty()||x<=stack2.peek()){
stack2.add(x);
}
}
public void pop() {
if(stack1.peek().equals(stack2.peek())){
stack2.pop();
}
stack1.pop();
}
public int top() {
return stack1.peek();
}
public int min() {
return stack2.peek();
}
}
/**
* Your MinStack object will be instantiated and called as such:
* MinStack obj = new MinStack();
* obj.push(x);
* obj.pop();
* int param_3 = obj.top();
* int param_4 = obj.min();
*/
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/330140.html
標籤:其他
