我试图从HackerRank解决Python3中的排序问题:https://www.hackerrank.com/challenges/fraudulent-activity-notifications/problem
这个问题需要在运行的基础上找到每个子列表的中值。在
由于超时终止,我的代码可以用于示例测试用例,但不完全适用于实际测试用例。我怀疑每次使用sort()查找中间值会导致时间延迟。在
如何改进我的代码?在
def activityNotifications(expenditure, d):
totalDays = len(expenditure)
notified = 0
for x in range(d, totalDays):
check = expenditure[x-d:x]
check.sort()
if d % 2 == 0:
median = (check[int(d/2)] + check[int((d-2)/2)])/2
else:
median = check[int((d-1)/2)]
if expenditure[x] >= median * 2:
notified += 1
return notified
为了在每次迭代中找到一个中间值,您需要对子数组进行排序。它不是真正有效的,尤其是当
d
不小的时候。每次迭代的时间复杂度是O(dlog(d))
。在要找到中值,我们需要一个排序数组,但不需要
sort()
方法。如果我们注意到每个expenditure[i]
都在[0;200]
范围内,那么计数排序在这里听起来是个好主意。基本上,我们用counts[i]
来计算每个数i
的频率。为了得到一个排序数组,我们只需要迭代j: counts[j] > 0
。在因此,如果
counts
为每个长度d
(区间[i; i + d)
)的间隔保持expenditure
个数的频率,我们最多可以通过检查counts
中的201
个数来找到一个中值(有关详细信息,请参阅代码)。移动到下一个间隔[i+1; i+d+1)
需要将数字i
的频率递减为counts[i]
,而增加i+d
的频率。 这种方法需要O(n*201)
时间和O(201)
空间复杂性。在现在,请参见下面的代码:
相关问题 更多 >
编程相关推荐