[英]I am having some trouble to optimize my code. Certain test cases are failing due to “exceeded time limit”. How can I optimize my code?
I tried to solve a question in Hackerrank.我试图在 Hackerrank 中解决一个问题。 I passed all the sample test cases but couldn't pass all the hidden test cases due to the "exceeded time limit" error.我通过了所有示例测试用例,但由于“超过时间限制”错误,无法通过所有隐藏测试用例。 The link to the problem question is: Fraudulent-activity notification问题问题的链接是: 欺诈活动通知
My code is as follows.我的代码如下。
#include <bits/stdc++.h>
using namespace std;
vector<string> split_string(string);
// Complete the activityNotifications function below.
int activityNotifications(vector<int> v, long int d) {
long int n,ex;
long double m;
long int cap=v.size();
long int notif=0;
n=d;
for(long int i=0;i<n&&n<cap;i++,n++)
{
ex=v[n];
sort(v.begin()+i, v.begin()+i+d);
if(d%2==0)
{
m=(v[(n+i-1)/2]+v[(n+i)/2])/2.0;
}
else
{
m=v[(n+i)/2];
}
if((m*2)>=ex)
{
notif++;
}
}
return (notif-1);
}
int main()
{
vector<int>v;
long int n,d;
long int item;
cin>>n>>d;
for(long int i=0;i<n;i++)
{
cin>>item;
v.push_back(item);
}
int res=activityNotifications(v,d);
cout<<res;
return 0;
}
How can I optimize this code?如何优化此代码? Please help.请帮忙。
For now, every step requires sorting with O(dlogd)
time, so overall time is about O(ndlogd)
目前,每一步都需要使用O(dlogd)
时间进行排序,因此总时间约为O(ndlogd)
You have to minimize time for median.你必须尽量减少中位数的时间。 There is an approach with min and max heaps ( example ) to treat all data untul current moment.有一种使用最小和最大堆( 示例)的方法来处理当前时刻的所有数据。 Median is element at the larger size heap for odd d
, and average of two heaps tops for even d
.中位数是奇数d
较大堆上的元素,偶数d
是两个堆顶部的平均值。
But you need median in rolling window.但是你需要滚动 window 的中位数。 So possible addition: make parallel data structure ref[]
(list/array working in cyclic manner) with references/pointers to heap nodes.所以可能的补充:使用指向堆节点的引用/指针制作并行数据结构ref[]
(以循环方式工作的列表/数组)。 When index leaves window (of size d
), remove corresponding node from a heap, then add new node with new value and update heaps and ref
.当索引离开 window (大小为d
)时,从堆中删除相应的节点,然后添加具有新值的新节点并更新堆和ref
。
Every step will require only O(logd)
time每一步只需要O(logd)
时间
Update: seems this topic contains links and descriptions of a lot of rolling window median
methods更新:似乎这个主题包含很多rolling window median
方法的链接和描述
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.