[英]The run time is too long
When I test it with code, there is no error, but it fails with a timeout.当我用代码测试它时,没有错误,但它因超时而失败。
Problem问题
The failure rate is defined as follows.故障率定义如下。 Number of players / number of players as far as stage is concerned The total number N of stages, the game can be currently stopped by the user.
就阶段而言的玩家数量/玩家数量 阶段的总数N,用户当前可以停止游戏。 .
.
Limitations限制
The number N of stages is a natural number of 1 or more and 500 or less.级数N是1以上500以下的自然数。 The length of the stage is 1 or more and 200,000 or less.
舞台的长度为1以上200,000以下。 Contains natural water above step 1 and below N + 1. Each natural number is currently being challenged by the user.
包含高于步骤 1 和低于 N + 1 的天然水。每个自然数目前都在受到用户的挑战。 N + 1 is the final stage.
N + 1 是最后阶段。 There is still a failure rate.
故障率还是有的。 The success rate of the stage is zero.
该阶段的成功率为零。
My code我的代码
def solution(N, stages):
fail = []
for i in range(1,N+1):
no_clear = stages.count(i)
he_stage = sum([stages.count(x) for x in range(i,N+2)])
if no_clear==0:
fail.append((i,0))
else:
fail.append((i,no_clear/he_stage))
fail=sorted(fail,key=lambda x: (-x[1],x[0]))
print(fail)
return [fail[i][0] for i in range(N)]
I suppose stages
is a list
.我想
stages
是一个list
。 Calling count
repeatedly on a list
has a very high complexity, specially if you're doing that in a loop.在
list
上重复调用count
具有非常高的复杂性,特别是如果您在循环中执行此操作。
You could use a cache or maybe simpler: replace stages.count(x)
by a collections.Counter
object call您可以使用缓存或更简单的方法:用
collections.Counter
对象调用替换stages.count(x)
before:前:
def solution(N, stages):
fail = []
for i in range(1,N+1):
no_clear = stages.count(i)
he_stage = sum([stages.count(x) for x in range(i,N+2)])
after:后:
import collections
def solution(N, stages):
fail = []
stages_counter = collections.Counter(stages)
for i in range(1,N+1):
no_clear = stages_counter[i]
he_stage = sum(stages_counter[x] for x in range(i,N+2))
This will reduce your complexity a great deal.这将大大降低您的复杂性。 Elements are counted once and for all.
元素被一劳永逸地计数。 Just access the dictionary in
O(1)
time once it's done.完成后只需在
O(1)
时间内访问字典。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.