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")
答案 0 :(得分:1)
由于您可以使用sort
方法(经过优化以避免执行代价高昂的冒泡排序或手动双循环,其复杂度O(n**2)
,并且列出非常大的列表),让我提出一些建议:
min
函数最小值必须是相邻值的绝对差值。由于列表是使用快速算法排序的,因此可以为您完成繁重的工作。
像这样:horse_str = [10, 5, 15, 17, 3, 8, 11, 28, 6, 55, 7]
sh = sorted(horse_str)
print(min(abs(sh[i]-sh[i+1]) for i in range(len(sh)-1)))
我也得到了1
(我希望我没有错过任何东西)