老师,我刚刚又优化了下速度,因为刚刚在leetcode试了之前的方法才击败了50%,现在这个击败96%
# -*- coding: UTF-8 -*
class MyQueue(object):
def __init__(self):
"""
Initialize your data structure here.
"""
self.input_stack = []
self.output_stack = []
def push(self, x):
"""
Push element x to the back of queue.
:type x: int
:rtype: None
"""
self.input_stack.append(x)
def pop(self):
"""
Removes the element from in front of queue and returns that element.
:rtype: int
"""
if self.empty():
return None
else:
if len(self.output_stack):
return self.output_stack.pop()
else:
# for i in xrange(0, len(self.input_stack)):
# self.output_stack.append(self.input_stack.pop())
length = len(self.input_stack)
self.output_stack = map(lambda x: self.input_stack.pop(), range(0, length))
return self.output_stack.pop()
def peek(self):
"""
Get the front element.
:rtype: int
"""
if self.empty():
return None
else:
if len(self.output_stack):
return self.output_stack[-1]
else:
# for i in xrange(0, len(self.input_stack)):
# self.output_stack.append(self.input_stack.pop())
length = len(self.input_stack)
self.output_stack = map(lambda x: self.input_stack.pop(), range(0, length))
return self.output_stack[-1]
def empty(self):
"""
Returns whether the queue is empty.
:rtype: bool
"""
return bool(len(self.input_stack) == 0 and len(self.output_stack) == 0)
展开