当我在类似于Leetcode的某些网站上尝试使用我的代码时,我意识到即使是类似的代码也可能具有相当大的性能(速度)差异。第一个是具有函数(我能够解决算法问题)的函数,另一个是for循环的形式(失败,超过了运行时间)。我不知道是什么使运行时间显着不同。 我首先认为输入函数与sys.stdin.readline()可能是原因,但我发现并没有太大的区别。这可能只是网站服务器分级中的一种偏爱,但我不禁认为以函数形式编写代码通常会更快。 希望我可以在这里获得一些帮助,以便使我对导致明显的运行时间差异的原因有一个清晰的答案。下面列出了2个代码。谢谢大家。 ''' '''
样本输入: 输出:import sys
def gen(case):
for _ in range(case):
cand=int(sys.stdin.readline().strip())
new=[0]*cand;
for i in range(cand):
resume, inter=map(int, sys.stdin.readline().strip().split())
new[resume-1]=inter;
yield new
def greedy(new):
count=1;
compare=1;
limit=new[0];
while limit>1:
if new[compare]<limit:
limit=new[compare];
count+=1;
compare+=1;
return count
if __name__=="__main__":
case=int(sys.stdin.readline().strip())
for p in gen(case):
print(greedy(p));
for _ in range(int(input())): # if __name__ =="__main__":
cand=int(input()); # gen function starts
new=[0]*cand;
for i in range(cand):
inp=input().split(' ');
for j in range(2):
inp[j]=int(inp[j]); # j=resume , inp[j]=inter
new[inp[0]-1]=inp[1]; # gen function ends
count=1; # greedy function starts
compare=1;
limit=new[0];
while limit>1:
if new[compare]<limit:
limit=new[compare];
count+=1;
compare+=1;
print(count); # greedy function ends
2
5
3 2
1 4
4 1
2 3
5 5
7
3 6
7 3
4 2
1 4
5 7
2 5
6 1
4
3 0 个答案:
没有答案