【发布时间】:2019-10-06 12:39:42
【问题描述】:
我正在解决这个问题:HackerRank 上的Farudulent Activity Notification。我已经完成了我的代码并且正在工作,但是对于非常大的输入,它也是低效。
我不知道,但经过我的努力,我能够为中等水平的问题提供很好的解决方案,但是对于非常大的输入,每次都会发生这种
timeout error。我已经尝试优化我的代码,但仍然出现超时错误。 我对这个问题和即将提出的问题的议程是:
- 如何为非常大的投入提高效率。它需要什么样的智慧。
- 如何达到该级别。我应该为此做些什么准备。
- 代码优化
我乐于学习,我真的很想学习如何编写更高级和优化的代码来让自己变得更好。我愿意努力工作。
我的算法:
- 对于这个问题,我们必须从
incrementing variable i到len(givenArray)-d- 取一个变量作为下一个要比较的变量,我的情况
iterate就是变量- 将特定数组的值传递给计数方法
countFraud()- 将其添加到计数变量中
- 递增迭代变量
代码:
# this is for counting the trailing array
def countFraud(arr, nextNum):
count = 0
median = 0.0
d = len(arr)
#for calculating the median correctly
arr.sort()
if d%2 != 0:
median = arr[int(d/2)]
else:
n = int(d/2)
median = (arr[n] + arr[n-1]) / 2
#now the opeartion for count from the array
if nextNum >= 2*median: count += 1
return count
# Complete the activityNotifications function below.
def activityNotifications(expenditure, d):
count = 0
iterate = d
# it will go upto the len of array - d, so that it will go upto the d length
# leaving the last element everytime for the comparision
for i in range(len(expenditure)-d):
count += countFraud(expenditure[i:iterate], expenditure[iterate])
iterate += 1
return count
现在我之前做了两个循环,将项目添加到new_array 并将其传递给countFraud()。但现在我已经对其进行了优化,并使其类似于O(N)。
我不知道,但由于Timeout Error,此代码并未针对所有 TC 提交。操作部分没有问题。这只是代码的效率。
超时错误输入示例:
200000 10000
输入链接 - Input Data
预期输出:
633
我已阅读这篇文章:HackerRank Environment 以了解时间问题。对于 Python/Python 3,它是 10 秒。我的代码肯定比values greater than 10^3 or 4 占用的更多。
我的代码已经成功通过了 3 次 TC。 请帮忙。谢谢你:)
【问题讨论】:
标签: python python-3.x sorting functional-programming time-limiting