leetcode interview questions 59 -. II maximum queue (Python)

Here Insert Picture Description
Problem solution :

Knowledge points:

  1. Deque: both ends of the queue can be a data structure / dequeue the.

  2. Encapsulated in python deque (deque):

    Adding elements

    deque supports adding elements from either end.

    • extend () add multiple elements from the right end
    • append () adds an element from the right end
    • extendleft () to add a plurality of elements from the left end, note the reverse input
    • appendleft () adds an element from the left end

    Gets the element

    • pop () Removes the element from the right
    • popleft () remove an element from the left
      note, deque is thread-safe, so you can remove elements from both ends at the same time in different threads.

    The above quote from: https: //www.jianshu.com/p/6928e420edb0

I thought this question:

  1. Main elements of the queue in order into the team
  2. Deque internal initialization enqueue an element, behind enqueued element if the element in the queue is less than it enqueue Otherwise, the elements of the queue inside is dequeued back enqueued element; i.e. deque inside elements are in descending order
  3. Back into the deque rule element is shown as step two
  4. This allows real-time to identify the main elements of the current maximum internal queue, the largest element in the team and head position deque

Achieve a: python package using queues and a queue deque
code is as follows:

import queue
class MaxQueue:

    def __init__(self):

    	self.queue = queue.Queue()
    	self.deque = queue.deque()
    	

    def max_value(self):


    	return self.deque[0] if self.deque else -1



    def push_back(self, value):

    	while self.deque and self.deque[-1] < value:
    		self.deque.pop()
    	self.deque.append(value)
    	self.queue.put(value)



    def pop_front(self):

    	if not self.deque: return -1
    	ans = self.queue.get()

    	#判断双端队列是否和主队列首元素相等,如果相等,最大值队列元素出队

    	if ans == self.deque[0]:
    		self.deque.popleft()
    	return ans

Achieve 2: Using the python queue list and deque;

code show as below:

class MaxQueue:

    def __init__(self):

    	self.queue = []
    	self.max_queue = []
    	

    def max_value(self):


    	return self.max_queue[0] if self.max_queue else -1



    def push_back(self, value):

    	while self.max_queue and self.max_queue[-1] < value:
    		self.max_queue = self.max_queue[0:-1]

    	self.max_queue.append(value)
    	self.queue.append(value)



    def pop_front(self):

    	if not self.max_queue: return -1

    	ans = self.queue.pop(0)

        #判断存储最大值的队列是否和主队列首元素相等,如果相等,最大值队列元素出队

    	if ans == self.max_queue[0]:
    		self.max_queue.pop(0)
    	return ans
Published 100 original articles · won praise 3 · views 10000 +

Guess you like

Origin blog.csdn.net/cy_believ/article/details/104911265