// Storage queue Queue<Integer> queue; // Monotonic two-way queue Deque<Integer> deque; public MaxQueue() { queue = new LinkedList<>(); deque = new LinkedList<>(); } public int max_value() { // empty return -1 non-empty return head of the queue return deque.isEmpty()? -1: deque.peekFirst(); } public void push_back(int value) { queue.offer(value); // delete in a loop until The values in the queue are greater than the current value, or the queue is empty while(!deque.isEmpty() && deque.peekLast() <value){ // When the queue is not empty, the current value is compared with the value at the end of the queue, if Is greater than, delete the tail value of the queue deque.removeLast(); } // After executing the above loop, the queue is either empty or the value is greater than the current value, and then the current value is added to the queue deque.offerLast(value ); } public int pop_front() { // Empty return -1 if (queue.isEmpty()){ return -1; } // If the head of the data queue and the monotonic two-way queue are equal if (queue.peek().equals(deque. peekFirst())){ // Monotonic two-way queues should also be popped to keep the elements of the two queues consistent deque.removeFirst(); } return queue.remove(); } public static void main(String[] args) { MaxQueue65 obj = new MaxQueue65(); obj.push_back(1); obj.push_back(2); System.out.println(obj.max_value()); System.out.println(obj.pop_front()); System.out.println (obj.max_value()); }
The sword refers to the maximum value of the Offer-65 queue
Guess you like
Origin blog.csdn.net/a792396951/article/details/114633539
Ranking