我正在尝试这个HackerRank problem。到目前为止,我已经完成了这段代码:
n = int(raw_input())
ar = []
for i in xrange(n):
ar.append(raw_input().split())
output = [0] * 1000000
count = [0] * 100
for a in ar:
count[int(a[0])] += 1
total = 0
for a in xrange(100):
old = count[a]
count[a] = total
total += old
for a in ar:
if ar.index(a) < n/2:
output[count[int(a[0])]] = '-'
else:
output[count[int(a[0])]] = a[1]
count[int(a[0])] += 1
for o in output:
if type(o) != str:
break
else:
print o,
在5个测试用例中,它只通过了一个。 2由于运行时间过长而超时,但现在不是我的首要任务。我的优先事项是通过其他2个完全失败的测试用例。我无法想象我可能出错的地方。我知道我可以让我的代码更有效率,但就目前而言,我专注于获得正确的输出。
答案 0 :(得分:1)
我怀疑你的所有问题(时间和正确性)都来自于使用ar.index(a)
来检查输入列表的前半部分是否有值。
该行总是非常慢(搜索列表需要O(N)时间),如果有两条相同的行,一行在输入的前半部分,一行在下半场。相反,在迭代列表时使用enumerate
来获取索引:
for i, a in enumerate(ar):
if i < n/2:
output[count[int(a[0])]] = '-'
else:
output[count[int(a[0])]] = a[1]
count[int(a[0])] += 1
您可以改进其他几项内容(例如制作output
长度n
,或将每个密钥转换为int
一次),但要删除对{{1}的调用可能是最重要的修复。