【剑指offer】59.2 队列的最大值

128 阅读1分钟

题目描述

在这里插入图片描述

// 59.2 队列的最大值

// 力扣
// 请定义一个队列并实现函数 max_value 得到队列里的最大值,要求函数m
// ax_value、push_back 和 pop_front 的均摊时间复杂度都是O(1)。
// 若队列为空,pop_front 和 max_value 需要返回 -1

题解

// 力扣
// 数组辅助法
// 执行用时:70 ms, 在所有 Java 提交中击败了6.10%的用户
// 内存消耗:46.3 MB, 在所有 Java 提交中击败了63.28%的用户
class MaxQueue {
	List<Integer> list;
	Queue<Integer> queue;

    public MaxQueue() {
		list = new ArrayList<Integer>();
		queue = new LinkedList<Integer>();
    }
    
    public int max_value() {
		if (queue.isEmpty())
			return -1;
		Collections.sort(list);
		return list.get(list.size() - 1);
    }
    
	// 从背后(back)入队
    public void push_back(int value) {
		queue.add(value);
		list.add(value);
    }
    
	// 从前面(front)出队
    public int pop_front() {
		if (queue.isEmpty())
			return -1;
		int out = queue.remove();
		list.remove(list.indexOf(out));
		return out;
    }
}

/**
 * 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();
 */



// 力扣
// 双端队列辅助法
// 执行用时:41 ms, 在所有 Java 提交中击败了55.00%的用户
// 内存消耗:46.4 MB, 在所有 Java 提交中击败了47.06%的用户
class MaxQueue {
	Deque<Integer> deque;
	Queue<Integer> queue;

    public MaxQueue() {
		deque = new LinkedList<Integer>();
		queue = new LinkedList<Integer>();
    }
    
    public int max_value() {
		if (queue.isEmpty())
			return -1;
		return deque.peekFirst();
    }
    
	// 从背后(back)入队
    public void push_back(int value) {
		while (!deque.isEmpty() && deque.peekLast() < value) {
			deque.pollLast();
		}
		deque.offerLast(value);
		queue.offer(value);
    }
    
	// 从前面(front)出队
    public int pop_front() {
		if (queue.isEmpty())
			return -1;
		int res = queue.poll();
		if (res == deque.peekFirst()) {
			deque.pollFirst();
		}
		return res;
    }
}