www.codingame.com
任务
Write a program which, using a given number of strengths,
identifies the two closest strengths and shows their difference with an integer
信息
n = Number of horses
pi = strength of each horse
d = difference
1 < n < 100000
0 < pi ≤ 10000000
我的代码当前
def get_dif(a, b):
return abs(a - b)
horse_str = [10, 5, 15, 17, 3, 8, 11, 28, 6, 55, 7]
n = len(horse_str)
d = 10000001
for x in range(len(horse_str)):
for y in range(x, len(horse_str) - 1):
d = min([get_dif(horse_str[x], horse_str[y + 1]), d])
print(d)
测试用例
[3,5,8, 9] outputs: 1
[10, 5, 15, 17, 3, 8, 11, 28, 6, 55, 7] outputs: 1
问题
它们都有效,但是下一次测试给了我一个很长的马的力量列表,我得到了**Process has timed out. This may mean that your solution is not optimized enough to handle some cases.
如何优化它?谢谢您!你知道吗
编辑一个
给定的默认代码
import sys
import math
# Auto-generated code below aims at helping you parse
# the standard input according to the problem statement.
n = int(input())
for i in range(n):
pi = int(input())
# Write an action using print
# To debug: print("Debug messages...", file=sys.stderr)
print("answer")
由于您可以使用
sort
方法(该方法经过优化,以避免手动执行代价高昂的冒泡排序或双循环,这类排序具有O(n**2)
复杂性,并且超时时有一个非常大的列表),因此让我提出一些建议:min
函数最小值必须是相邻值的绝对差值。因为列表是使用快速算法排序的,所以繁重的工作是为您完成的。你知道吗
像这样:
我也因此得到
1
(我希望我没有错过任何东西)相关问题 更多 >
编程相关推荐