0
点赞
收藏
分享

微信扫一扫

Leetcode—剑指offer—Day1

剑指 Offer 30. 包含min函数的栈

定义栈的数据结构,请在该类型中实现一个能够得到栈的最小元素的 min 函数在该栈中,调用 min、push 及 pop 的时间复杂度都是 O(1)。

  • 解法一:一看取最小这种需要排序的,第一反应就是PriorityQueue,存储栈所有元素,并且默认按升序排,栈弹出时,优先队列remove(s.peek())就行,只能说Java集合太方便了
class MinStack {
    Stack<Integer> s ;
    PriorityQueue<Integer> q ; 
    /** initialize your data structure here. */
    public MinStack() {
        s = new Stack<Integer>();
        q = new PriorityQueue<Integer>();
    }
    
    public void push(int x) {
        s.push(x);
        q.add(x);
    }
    
    public void pop() {
        q.remove(s.peek());
        s.pop();
    }
    
    public int top() {
        return s.peek();
    }
    
    public int min() {
        return q.peek();
    }
}
举报

相关推荐

0 条评论