数据结构与算法(3):队列的最大值

这里是采用了java的队列LinkedBlockingQueue,所以题目解答起来难度不大,最大值那采用了stream流来获取

/**
 * @author lenyuqin
 * @data 2021/1/19
 * 剑指 Offer 59 - II. 队列的最大值
 * 请定义一个队列并实现函数 max_value 得到队列里的最大值,要求函数max_value、push_back 和 pop_front 的均摊时间复杂度都是O(1)。
 * <p>
 * 若队列为空,pop_front 和 max_value需要返回 -1
 */
public class MaxQueue {
    
    
    public MaxQueue() {
    
    
        this.linkedBlockingQueue = new LinkedBlockingQueue<>();
    }

    private LinkedBlockingQueue<Integer> linkedBlockingQueue;


    public int max_value() {
    
    
        if (linkedBlockingQueue.size() == 0) {
    
    
            return -1;
        } else {
    
    
            return linkedBlockingQueue.stream().max(Integer::compareTo).get();
        }
    }


    public void push_back(int value) {
    
    
        linkedBlockingQueue.offer(value);
    }


    public int pop_front() {
    
    
        if (linkedBlockingQueue.size() == 0) {
    
    
            return -1;
        } else {
    
    
            return linkedBlockingQueue.poll();
        }
    }

    /**
     * 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();
     */
    public static void main(String[] args) throws InterruptedException {
    
    
        MaxQueue maxQueue = new MaxQueue();
        maxQueue.push_back(1);
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_44777669/article/details/112850891