简体   繁体   English

在一组三个向量中找到最接近的三元组?

[英]Finding closest triplet in a set of three vectors?

Given three vectors of double, I want to pair every element in each vector such that the difference between the largest and smallest element in each triple is minimized, and every element of every vector is part of a triple.给定三个双精度向量,我想对每个向量中的每个元素进行配对,以使每个三元组中最大和最小元素之间的差异最小化,并且每个向量的每个元素都是三元组的一部分。 Right now, I'm using std::lower_bound() :现在,我正在使用std::lower_bound()

double closest(vector<double> const& vec, double value){ auto const ret = std::lower_bound(vec.begin(), vec.end(), value); return(*ret); }

int main(){
    vector<double> a, b, c; vector<vector<double>> triples;
    for(auto x : a){
       triples.push_back({x, closest(b, x), closest(c, x)});
    }
}

Pretend a, b, and c here are populated with some values.假设 a、b 和 c 在这里填充了一些值。 The problem is, lower_bound() returns the nearest element not less than the argument.问题是, lower_bound()返回不小于参数的最近元素。 I would also like to consider elements less than the argument.我还想考虑比论点少的元素。 Is there a nice way to to this?有什么好的方法吗?

My solution was to implement a binary search terminating in a comparison of neighboring elements.我的解决方案是在相邻元素的比较中实现二进制搜索。 Another possible solution is to iterate over the elements of each vector/array, adjusting the index as necessary to minimize the difference (which may compare to binary search with an ideal complexity of $O(\log{n})$?):另一种可能的解决方案是迭代每个向量/数组的元素,根据需要调整索引以最小化差异(这可能与理想复杂度为 $O(\log{n})$? 的二分查找相比较):

int solve(int A[], int B[], int C[], int i, int j, int k) 
{  
        int min_diff, current_diff, max_term; 
  
        min_diff = Integer.MAX_VALUE; 
  
        while (i != -1 && j != -1 && k != -1)  
        { 
            current_diff = abs(max(A[i], max(B[j], C[k]))  
                            - min(A[i], min(B[j], C[k]))); 
  
            if (current_diff < min_diff) 
                min_diff = current_diff; 
  
            max_term = max(A[i], max(B[j], C[k])); 
            if (A[i] == max_term) 
                i -= 1; 
            else if (B[j] == max_term) 
                j -= 1; 
            else
                k -= 1; 
        } 
          
        return min_diff; 
    } 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM