[英]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.