leetcode155. 最小栈和面试题59 - II. 队列的最大值

155. 最小栈

设计一个支持 push,pop,top 操作,并能在常数时间内检索到最小元素的栈。

push(x) – 将元素 x 推入栈中。
pop() – 删除栈顶的元素。
top() – 获取栈顶元素。
getMin() – 检索栈中的最小元素。
示例:

MinStack minStack = new MinStack();
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
minStack.getMin(); --> 返回 -3.
minStack.pop();
minStack.top(); --> 返回 0.
minStack.getMin(); --> 返回 -2.

class MinStack {
       private  Stack<Integer> stack1;//正常的栈
       private  Stack<Integer> stack2;//记录最小值的栈
    /** initialize your data structure here. */
    public MinStack() {
        stack1=new Stack<Integer>();
        stack2=new Stack<Integer>();
    }
    
    public void push(int x) {
        stack1.push(x);
        if(stack2.isEmpty()||stack2.peek()>x)
        {
            stack2.push(x);
        }
        else
        stack2.push(stack2.peek());
    }
    
    public void pop() {
        stack1.pop();
        stack2.pop();
    }
    
    public int top() {
        return stack1.peek();
    }
    
    public int getMin() {
        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.getMin();
 */

面试题59 - II. 队列的最大值

请定义一个队列并实现函数 max_value 得到队列里的最大值,要求函数max_value、push_back 和 pop_front 的均摊时间复杂度都是O(1)。

若队列为空,pop_front 和 max_value 需要返回 -1

示例 1:

输入:
[“MaxQueue”,“push_back”,“push_back”,“max_value”,“pop_front”,“max_value”]
[[],[1],[2],[],[],[]]
输出: [null,null,null,2,1,2]
示例 2:

输入:
[“MaxQueue”,“pop_front”,“max_value”]
[[],[],[]]
输出: [null,-1,-1]
限制:
• 1 <= push_back,pop_front,max_value的总操作数 <= 10000
• 1 <= value <= 10^5

class MaxQueue {
private Queue<Integer>queue;
private Deque<Integer>deque;//双端队列
    public MaxQueue() {
    queue=new LinkedList<Integer>();
    deque=new LinkedList<Integer>();
    }
    
    public int max_value() {
        if(deque.isEmpty())
        return -1;
      return deque.peekFirst();//返回双端队列的最前面
    }
    
    public void push_back(int value) {
            queue.offer(value);
       while(!deque.isEmpty()&&deque.peekLast()<value)
           deque.pollLast();//从deque双端队列的末尾判断,如果新的value大于deque尾端的值,那么deque一直进行pop_back操作,直到尾端的值大于等于value 或者为空,再将value压入deque的尾部
        deque.offerLast(value);
    }
    
    public int pop_front() {
    if(queue.isEmpty())
    return -1;
    int temp=queue.poll();//queue必须先出队列
      if(temp==deque.peekFirst())//queue首部的值等于deque首部的值,说明当前的是最大值
      deque.pollFirst();
      return temp;

    }
}

/**
 * Your MaxQueue object will be instantiated and called as such:
 * MaxQueue obj = new MaxQueue();
 * int param_1 = obj.max_value();
 * obj.push_back(value);
 * int param_3 = obj.pop_front();
 */

猜你喜欢

转载自blog.csdn.net/qq_38765865/article/details/104731614