【发布时间】:2018-09-22 21:23:27
【问题描述】:
给定未排序的向量 {6.0, 3.02, 4.2, 5.3} 并给出阈值 0.1,如何在 C++ 中的给定阈值内有效地找到值 3(例如)的第一个匹配项? 我目前的实现如下,但复杂度为 O(n)。如果可能,我想将其改进为 O(log n)。提前非常感谢
std::vector<double> array = {6.0, 3.02, 4.2, 5.3};
double val = 3 // the to be found value within the array above
double thresh = 0.1; // max threshold of the matching value
double found; // the matching value
for (int i = 0; i < array.size(); i++){
if ( abs(array[i] - val) < thresh){
found = array[i];
}
}
输出应该是 3.02,因为它是在允许的阈值 0.1 内给定数组中第一个最接近 3 的匹配项
编辑:如果我能负担得起预先对向量进行排序,我该如何将上述搜索重新实现为 O(log n)?谢谢
【问题讨论】:
-
我认为不先对数组进行排序就不可能击败 O(n)
-
如果数组未排序或以任何方式特别组织,则必须扫描所有元素。
-
数据作为向量给出?如果是这样,就没有运气
-
顺便说一句,如果您使用 C 库中的一个,请注意
abs(),它会将数字四舍五入为int -
您的问题与实现不匹配 - 您的算法会找到 "
val的 0.1 内的第一个现有值",而不是 "将现有值关闭到 @ 987654325@"
标签: c++ algorithm performance