DAY 4 队列和堆栈
太太太累了 两天做了一道题 自闭
622. 设计循环队列
class MyCircularQueue:
def __init__(self, k: int):
"""
Initialize your data structure here. Set the size of the queue to be k.
"""
self.queue = [None]*k
self.head = None
self.tail = None
self.size = k
def enQueue(self, value: int) -> bool:
"""
Insert an element into the circular queue. Return true if the operation is successful.
"""
if not self.isFull():
if not self.isEmpty():
self.tail = (self.tail+1) % self.size
self.queue[self.tail] = value
return True
else:
#对于self.head的初始化非常重要,不然下面一直self.queue[self.head] = None 的时候,找不到self.head的值,就是对于一个索引值为None的地方赋值为None,就会出错
self.head = self.tail = 0
self.queue[0] = value
return True
else:
return False
def deQueue(self) -> bool:
"""
Delete an element from the circular queue. Return true if the operation is successful.
"""
if not self.isEmpty():
self.queue[self.head] = None
self.head = (self.head +1) % self.size
return True
else:
return False
def Front(self) -> int:
"""
Get the front item from the queue.
"""
if not self.isEmpty():
return self.queue[self.head]
else:
return -1
def Rear(self) -> int:
"""
Get the last item from the queue.
"""
if not self.isEmpty():
return self.queue[self.tail]
else:
return -1
def isEmpty(self) -> bool:
"""
Checks whether the circular queue is empty or not.
"""
for i in self.queue:
if i != None:
return False
break
return True
def isFull(self) -> bool:
"""
Checks whether the circular queue is full or not.
"""
for i in self.queue:
if i == None:
return False
break
return True
# Your MyCircularQueue object will be instantiated and called as such:
# obj = MyCircularQueue(k)
# param_1 = obj.enQueue(value)
# param_2 = obj.deQueue()
# param_3 = obj.Front()
# param_4 = obj.Rear()
# param_5 = obj.isEmpty()
# param_6 = obj.isFull()
虽然很累但是还想复盘一下,这个题对于empty和full的判断比较有意思。还有就是,坑爹的head的初始化!!很重要!!
还有就是对于enqueue操作,初始化很重要,如果不判断是否为空,那么head的值和tail的值就都是None,无法进行下面的计算,这个很容易给忽视,但是dequeue的时候,就不需要初始化了。
#503 下一个更大元素 II
题目描述:给定一个循环数组(最后一个元素的下一个元素是数组的第一个元素),输出每个元素的下一个更大元素。数字 x 的下一个更大的元素是按数组遍历顺序,这个数字之后的第一个比它更大的数,这意味着你应该循环地搜索它的下一个更大的数。如果不存在,则输出 -1。
这个题太开心了,第一次一次提交就A了的题
思路是:
1、先把原数组复制两遍连接起来,命名为anslist
2、对于原数组nums里的每一个元素i,查找范围是在anslist里面[i+1,i+nums的长度]
3、若是找见了,就把ans里的值更改,找不见则仍然为-1
class Solution:
def nextGreaterElements(self, nums):
lenth1 = len(nums)
anslist = nums + nums
lenth2 = len(anslist)
ans = [-1] * lenth1
for i in range(lenth1):
for j in range(lenth2)[i+1:i+lenth1]:
if anslist[j] > anslist[i]:
ans[i] = anslist[j]
break
return ans
本以为跟循环队列有点像,但是似乎关系不大emm