【发布时间】:2020-04-11 00:45:13
【问题描述】:
这个问题可能用到了python中栈的概念。 我的代码如下,但总是出现 Time Limit Exceed (TLE) 错误。 我认为问题是由于两个循环,我设计的算法太慢了。 我想知道如何实现堆栈的概念并在这个问题中只使用一个循环。请指导我并帮我修改代码,非常感谢。
输入:包括一行,包含多个整数,代表每次的得分,数字之间用空格隔开
输出:包括一行,包含多个整数,表示每个分数增加时的间隔频率(如果分数不增加,则返回0),数字之间用空格隔开
inp = [int(i) for i in input().split()]
#create a function to calculate intervals
def cal_interval(lst):
lenth = len(inp)
output_lst = []
for i in range(lenth):
#set counter
count = 1
#set iteraion number
iter_num = 0
for j in range(i+1, lenth):
iter_num += 1
if inp[j] > inp[i]:
output_lst.append(count)
break
else:
count += 1
if iter_num == (lenth-i-1):
output_lst.append(0)
break
#last number
output_lst.append(0)
#from int list transformed into str list
output_lst = [str(i) for i in output_lst]
#join by spaces
space = ' '
interval_str = space.join(output_lst)
return interval_str
print (cal_interval(inp))
有如下两组测试数据,
Sample Input 1: 89 56 78 9 81 7
Sample Output 1: 0 1 2 1 0 0
Sample Input 2: 76 3 60 57 11 72 73 86 27 91 56 58 21 2
Sample Output 2: 7 1 3 2 1 1 1 2 1 0 1 0 0 0
【问题讨论】:
-
这能回答你的问题吗? Implementing Stack with Python
-
看collections.deque。如文档中所述:双端队列是堆栈和队列的概括
-
为什么第二个输出不是:
0 1 0 0 ...? -
我的解释如下,对于76,有7个区间达到86,高于76。对于3,只有1个区间达到60,高于3。对于60 ,有3个区间达到72,高于3.以此类推...
标签: python data-structures stack