【发布时间】:2019-01-24 14:55:55
【问题描述】:
我有一个关于 Python 堆栈的问题。我尝试在 Hackerrank 中解决 Maximum Element 任务:
你有一个空序列,你会得到 N 个查询。每个查询 是以下三种类型之一:
1 x -Push the element x into the stack. 2 -Delete the element present at the top of the stack. 3 -Print the maximum element in the stack.输入的第一行包含一个整数 N。接下来的 N 行每行 包含上述查询。 (保证每次查询都是 有效。)
为了解决这个问题,我写了这样的东西:
class Stack:
def __init__(self):
self.items = []
def push(self, item):
self.items.append(item)
def pop(self):
return self.items.pop()
def maxEl(self):
return max(self.items)
s = Stack()
for i in range(int(input())):
n = input().split()
if n[0] == '1':
s.push(int(n[1]))
elif n[0] == '2':
s.pop()
else:
print(s.maxEl())
它可以工作,但显然太慢了,我只通过了 28 个测试用例中的 18 个(因为超时)。我找到了一个类似的解决方案,而且速度够快,但我不明白为什么:
class Stack:
def __init__(self):
self.arr = [0]
self.max = [0]
def push(self, data):
self.arr.append(data)
if self.max[-1] <= data:
self.max.append(data)
def pop(self):
if self.arr[-1] == self.max[-1]:
self.max.pop()
self.arr.pop()
N = int(input())
s = Stack()
for _ in range(N):
x = str(input())
if x[0] == '1':
s.push(int(x[2:]))
elif x[0] == '2':
s.pop()
else:
print(s.max[-1])
谁能解释一下为什么我的代码表现不佳?谢谢。
【问题讨论】: