[英]fastest way to get the maximal difference between 2 vectors
I would like to get ideas for finding a fast way to get the maximal difference between 2 vectors as if they're accumulated . 我想获得一些想法,寻找一种快速的方法来获得两个向量之间的最大差, 就好像它们是累积的一样 。
For example, (not accumulated yet) 例如,(尚未累积)
vector<int> vec1 = {10, 30, 20, 40 };
vector<int> vec2 = {5, 10, 5, 8 };
the naive way to get the result, is to accumulate them first into new vectors so: 获得结果的简单方法是先将它们累加到新的向量中,这样:
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};
ie: 即:
accumulated_vec1 = {10,40,60,100};
accumulated_vec2 = {5,15,20,28};
Then, the result is the max between abs(accumulated_vec1[i]-accumulated_vec2[i])
while 0 <= i <= 3. 然后,结果是
abs(accumulated_vec1[i]-accumulated_vec2[i])
之间的最大值,而0 <= i <= 3。
so result = 72
(when i==3) 因此
result = 72
(当i == 3时)
a faster way can be by representing the vectors by 1 number(even 0.10302040)... but I can't find it helpful :\\ Think that I have millions pairs of the 2 vectors vec1 and vec2, and I am trying to avoid calculating the accumulated vectors for each of pair.. sorry if it's not clear but if I find a solution, I'll answer this annoying question. 更快的方法是用1个数字表示偶数(甚至为0.10302040)...但是我觉得它没有帮助:\\认为我有2对向量vec1和vec2数百万对,因此我试图避免计算每个对的累加向量..对不起,如果不清楚,但是如果我找到解决方法,我将回答这个令人讨厌的问题。
Fastest way... 最快的方法...
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;
}
No other vector construction, just moving pointers that are even faster than getting elements per their index each time. 没有其他向量构造,只是移动指针,其速度甚至比每次按其索引获取元素还要快。
Take a look at the code below. 看一下下面的代码。 Does this do what you are asking?
这符合您的要求吗?
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;
}
Here is my version for your problem 这是您遇到的问题我的版本
int getAccumulatedForIndex(int index, vector<int> &vec) {
if (index == 0) {
return vec.at(index);
}
return vec.at(index) + getAccumulatedForIndex(index - 1, vec);
}
and than 然后
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;
}
hope that's it what you want 希望就是你想要的
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.