Implement Stack using Queues
这题是无法做到摊还O(1)的,要不pop浪费时间,要不push浪费时间,个人觉得什么双队列,单队列都没什么意义,下面是O(n)pop的算法
class MyStack(object):
def __init__(self):
"""
Initialize your data structure here.
"""
self.queue = collections.deque()
self._queue = collections.deque()
def push(self, x):
"""
Push element x onto stack.
:type x: int
:rtype: void
"""
self.queue.appendleft(x)
def pop(self):
"""
Removes the element on top of the stack and returns that element.
:rtype: int
"""
while len(self.queue) > 1:
self._queue.appendleft(self.queue.pop())
result = self.queue.pop()
while self._queue:
self.queue.appendleft(self._queue.pop())
return result
def top(self):
"""
Get the top element.
:rtype: int
"""
while len(self.queue) > 1:
self._queue.appendleft(self.queue.pop())
return self.queue[0]
def empty(self):
"""
Returns whether the stack is empty.
:rtype: bool
"""
return not self.queue and not self._queue
# Your MyStack object will be instantiated and called as such:
# obj = MyStack()
# obj.push(x)
# param_2 = obj.pop()
# param_3 = obj.top()
# param_4 = obj.empty()
Implement Queue using Stacks
因为栈的特性,这里如果利用双栈实现queue的话虽然可能单个操作时间复杂度较高,但是摊还后还是O(1)的
class MyQueue(object):
def __init__(self):
"""
Initialize your data structure here.
"""
self.stack = []
self._stack = []
def push(self, x):
"""
Push element x to the back of queue.
:type x: int
:rtype: void
"""
self.stack.append(x)
def pop(self):
"""
Removes the element from in front of queue and returns that element.
:rtype: int
"""
if self._stack:
return self._stack.pop()
while self.stack:
self._stack.append(self.stack.pop())
return self._stack.pop()
def peek(self):
"""
Get the front element.
:rtype: int
"""
if self._stack:
return self._stack[-1]
while self.stack:
self._stack.append(self.stack.pop())
return self._stack[-1]
def empty(self):
"""
Returns whether the queue is empty.
:rtype: bool
"""
return not self._stack and not self.stack
# Your MyQueue object will be instantiated and called as such:
# obj = MyQueue()
# obj.push(x)
# param_2 = obj.pop()
# param_3 = obj.peek()
# param_4 = obj.empty()