带有总和CPP的子阵列
- IAM由于复杂性O(n logn)而导致误差为TLE,而给定的QS需要在O(n)中求解。
- 需要找到m.find()方法的替代方案,因为它正在采用O(logN)复杂性,并且总复杂性变为O(nlog n)。
vector<int> subarraySum(int a[], int n, long long s)
{
vector<int> result;
map<int,int>m;
map<int,int>::iterator it;
int b[n];
b[0]=a[0];
for(int i=1;i<n;i++){
b[i]=b[i-1]+a[i];
}
for(int i=0;i<n;i++){
m.insert({ b[i],i });
}
for(it=m.begin();it!=m.end();it++){
if((it->first-s)==0){
result.push_back(1);
result.push_back((it->second)+1);
break;
}
if(m.find(it->first-s)!=m.end()){
result.push_back(m[it->first-s]+2);
result.push_back((it->second)+1);
break;
}
}
if(result.empty())
result.push_back(-1);
return result;
}
- Iam getting error as TLE due to complexity O(n logn) whereas given Qs needs to be solved in O(n).
- Need to find alternative of m.find() method as it is taking O(logn) complexity and total complexity becomes O(nlog n).
vector<int> subarraySum(int a[], int n, long long s)
{
vector<int> result;
map<int,int>m;
map<int,int>::iterator it;
int b[n];
b[0]=a[0];
for(int i=1;i<n;i++){
b[i]=b[i-1]+a[i];
}
for(int i=0;i<n;i++){
m.insert({ b[i],i });
}
for(it=m.begin();it!=m.end();it++){
if((it->first-s)==0){
result.push_back(1);
result.push_back((it->second)+1);
break;
}
if(m.find(it->first-s)!=m.end()){
result.push_back(m[it->first-s]+2);
result.push_back((it->second)+1);
break;
}
}
if(result.empty())
result.push_back(-1);
return result;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您应该学习滑动窗口算法: httpps://en.wikipedia.org/wikipedia.org/wiki/wiki/wiki/streaming_algorith_algorith_algorithm < /a>
You are supposed to learn the sliding window algorithm: https://en.wikipedia.org/wiki/Streaming_algorithm