Leetcode - Design Circular Queue (Python)

preview_player
Показать описание
April 2021 Leetcode Challenge
Leetcode - Design Circular Queue #622
Difficulty: Medium
Рекомендации по теме
Комментарии
Автор

I've watched a ton of these videos trying to understand circular queues and this by far was the most easy to follow, and has the simplest and cleanest code. Thanks for your work.

bolvarsdad
Автор

The most concise and clear explanations in all of youtube, thank you so much for your videos!

rutvijsupekar
Автор

Thanks for explaining the Rear method! I was wondering why it was -1

janmichaelaustria
Автор

What happens when tail ends up at the 0 index and you try to return list[-1] ?

julianelmasry
Автор

why not use a linked list to implement the circular queue?

Cloud-
Автор

Hi theres something i dont understand. The tail goes out of range after a few enQueues and deQueues because there are no more 'None'. Why do u not get this problem?

jiakai
Автор

My Python Implementation:

class MyCircularQueue(object):

def __init__(self, k):
"""
:type k: int
"""
self.size = 0
self.k = k
self.arr = [None] * k
self.tail = -1 # -1 because we haven't added anything in the queue
self.head = 0

def enQueue(self, value):
"""
:type value: int
:rtype: bool
"""
if self.size >= self.k:
return False

self.tail = (self.tail + 1) % self.k
if not self.arr[self.tail]:
self.arr[self.tail] = value
self.size += 1
return True

def deQueue(self):
"""
:rtype: bool
"""
if self.isEmpty():
return False
self.arr[self.head] = None
self.head = (self.head + 1) % self.k
self.size -= 1
return True

def Front(self):
"""
:rtype: int
"""
if self.isEmpty():
return -1
return self.arr[self.head]

def Rear(self):
"""
:rtype: int
"""
if self.isEmpty():
return -1
return self.arr[self.tail]

def isEmpty(self):
"""
:rtype: bool
"""
return self.size == 0


def isFull(self):
"""
:rtype: bool
"""
return self.size == self.k

edwardteach