Design Circular Queue - LeetCode
Design Circular Queue - LeetCode
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
원형 큐에 대해 배웠다. 알고리즘 수업 때 간단하게 배우고 지나쳤던 기억이 있는데 다시한번 상기시킬 수 있는 기회가 되어서 좋았다. 일반적인 큐와 비교해서 FIFO 구조를 가진다는 공통점이 있지만 마지막 위치와 시작위치가 연결되는 원형의 구조를 가지고 있는 자료구조이다.
마지막 코드 부분에 isEmpty ,isFull 부분을 통해서 파이썬의 간결함에 대해 다시한번 감탄하게 되었다.
풀이
class MyCircularQueue:
def __init__(self,k:int):
self.q = [None] * k
self.maxLen = k
self.p1 = 0
self.p2 = 0
def enQueue(self,value:int)-> bool:
if self.q[self.p2] is None:
self.q[self.p2] = value
self.p2 = (self.p2+1) % self.maxLen
return True
else:
return False
def deQueue(self)-> bool:
if self.q[self.p1] is None:
return False
else:
self.q[self.p1] = None
self.p1 = (self.p1+1) % self.maxLen
return True
def Front(self)-> int:
return -1 if self.q[self.p1] is None else self.q[self.p1]
def Rear(self)-> int:
return -1 if self.q[self.p2-1] is None else self.q[self.p2-1]
def isEmpty(self)-> bool:
return self.p1 == self.p2 and self.q[self.p1] is None
def isFull(self)->bool:
return self.p1 == self.p2 and self.q[self.p1] is not None
'IT > 알고리즘' 카테고리의 다른 글
[Leetcode]23. Merge k Sorted Lists (0) | 2020.10.06 |
---|---|
[Leetcode]641. Design Circular Deque (0) | 2020.10.06 |
[Leetcode]232. Implement Queue using Stacks (0) | 2020.10.06 |
[Leetcode]225. Implement Stack using Queues (0) | 2020.10.06 |
[Leetcode]316. Remove Duplicate Letters (0) | 2020.10.06 |