我最近在做Codility的测试,卡在了“Max Counters”这一题上(链接:https://codility.com/demo/take-sample-test/max_counters)。我的第一个明显的解决方案如下:
def solution(N, A):
counters = N * [0];
for a in A:
if 1 <= a <= N:
counters[a - 1] += 1;
elif a == N + 1:
counters = N * [max(counters)];
return counters
目前的方法可以正常运行,但由于每次调用max counters都会填充整个数组,所以耗费时间较长。
因此,我提出了以下解决方案,对于小规模的输入数据表现良好,但对于中等和大型数据则随机出现错误结果。
def solution(N, A):
counters = N * [0];
current_max = 0;
last_update = 0;
for a in A:
if 1 <= a <= N:
counters[a - 1] += 1;
if counters[a - 1] < last_update:
counters[a - 1] = last_update + 1;
if counters[a - 1] > current_max:
current_max = counters[a - 1];
elif a == N + 1:
last_update = current_max;
for i in xrange(len(counters)):
if counters[i] < last_update:
counters[i] = last_update;
return counters
我似乎无法弄清楚它有什么问题。