[英]fastest way to get the maximal difference between 2 vectors
我想获得一些想法,寻找一种快速的方法来获得两个向量之间的最大差, 就好像它们是累积的一样 。
例如,(尚未累积)
vector<int> vec1 = {10, 30, 20, 40 };
vector<int> vec2 = {5, 10, 5, 8 };
获得结果的简单方法是先将它们累加到新的向量中,这样:
vector<int> accumulated_vec1 = {10, 10+30, 10+30+20, 10+30+20+40};
vector<int> accumulated_vec2 = {5, 5+10, 5+10+5, 5+10+5+8};
即:
accumulated_vec1 = {10,40,60,100};
accumulated_vec2 = {5,15,20,28};
然后,结果是abs(accumulated_vec1[i]-accumulated_vec2[i])
之间的最大值,而0 <= i <= 3。
因此result = 72
(当i == 3时)
更快的方法是用1个数字表示偶数(甚至为0.10302040)...但是我觉得它没有帮助:\\认为我有2对向量vec1和vec2数百万对,因此我试图避免计算每个对的累加向量..对不起,如果不清楚,但是如果我找到解决方法,我将回答这个令人讨厌的问题。
最快的方法...
int maxDiff(const vector<int> &v1, const vector<int> &v2) {
int maxDiff(0), diff(0);
for (auto it1 = v1.begin(), it2 = v2.begin(); it1 != v1.end() && it2 != v2.end(); ++it1, ++it2) {
diff += *it1-*it2;
maxDiff = max(abs(diff), maxDiff);
}
return maxDiff;
}
没有其他向量构造,只是移动指针,其速度甚至比每次按其索引获取元素还要快。
看一下下面的代码。 这符合您的要求吗?
vector<int> accumulated_vec;
accumulated_vec.resize(vec1.size());
accumulated_vec[0] = vec1[0] - vec2[0];
for(int i = 1; i < accumulated_vec.size(); i++)
{
accumulated_vec[i] = accumulated_vec[i-1] + (vec1[i] - vec2[i]);
cout << accumulated_vec[i] << endl;
}
这是您遇到的问题我的版本
int getAccumulatedForIndex(int index, vector<int> &vec) {
if (index == 0) {
return vec.at(index);
}
return vec.at(index) + getAccumulatedForIndex(index - 1, vec);
}
然后
int getAccumulatedMax(vector<int> vec1, vector<int> vec2) {
if (vec1.size() != vec2.size()) { // don't much each other
return -1;
}
int max = -1;
for (int i = 0; i < vec1.size(); ++i) {
int currentMax = abs(getAccumulatedForIndex(i, vec1) - getAccumulatedForIndex(i, vec2));
if (currentMax > max) {
max = currentMax;
}
}
return max;
}
希望就是你想要的
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.