【发布时间】:2016-09-16 00:22:55
【问题描述】:
我一直在使用 python 解决黑客级别的 Bonetrousle 问题。几个小时后,下面的代码通过了所有测试用例,除了一个超时。任何有关如何使代码更快的建议将不胜感激。我相信问题在于处理其余部分的代码,我将 cmets 放在它的下方和上方,这样很容易找到。不幸的是,我不知道如何重构它以使其运行得更快。
我写的代码得到了所有测试用例的正确答案,我已经在 pycharm 中验证了这一点。唯一的问题是对于黑客级别的测试用例之一来说它会变慢。
这里是问题的链接https://www.hackerrank.com/challenges/bonetrousle
firstLine = int(input())
for a in range(0, firstLine):
nums = input()
numsArr = list(map(int, nums.split(" ")))
n = numsArr[0]
k = numsArr[1]
b = numsArr[2]
num1 = 0
rem = 0
answer = True
remAdded = False
count = 0
boxArr = []
for i in range(1, b+1):
count += i
boxArr.append(i)
num1 = (n - count)//b
rem = (n - count)%b
for j in range(0, len(boxArr)):
boxArr[j] = boxArr[j] + num1
if boxArr[j] > k:
answer = False
# In below code -> if there is a remainder I am adding it to an element in the array that has box numbers
# I check to see if I can add the remainder to an element in the array
#without that element exceeding k, the number of sticks. If I can't then the bool remAdded doesn't get set to True
# The below code works but it seems inefficient and looks like the problem
if rem == 0:
remAdded = True
elif answer != False:
for r in range(len(boxArr) - 1, 0, -1):
if boxArr[r] + rem <= k and r == len(boxArr) - 1:
boxArr[r] = boxArr[r] + rem
remAdded = True
break
else:
if boxArr[r] + rem <= k and (boxArr[r] + rem) not in boxArr:
boxArr[r] = boxArr[r] + rem
remAdded = True
break
# above is code for dealing with remainder. Might be the problem
if answer == False or remAdded == False:
print(-1)
elif 0 in boxArr:
print(-1)
else:
for z in range(0, len(boxArr)):
if z != len(boxArr) - 1:
print(boxArr[z], end =" ")
else:
print(boxArr[z])
【问题讨论】: