【发布时间】:2018-11-09 21:49:44
【问题描述】:
给定一个向量向量,是否有最佳方法来确定保持全局最小值的向量的索引? Big-O 表示法的复杂度是多少?
#include <algorithm>
#include <iostream>
#include <vector>
unsigned getMinimumIndex(std::vector<std::vector<unsigned>> const& a) {
if (!a.size())
return 0;
unsigned ret = 0; unsigned temp; unsigned global = 1 << 31;
for (std::size_t idx = 0; idx < a.size(); ++idx) {
if ((temp = *std::min_element(std::begin(a[idx]), std::end(a[idx]))) < global) {
global = temp;
ret = idx;
}
}
return ret;
}
int main() {
std::vector<std::vector<unsigned>> a = {{2, 4, 6, 8}, {3, 9, 5, 7},
{3, 4, 4, 3}, {2, 8, 3, 2},
{4, 4, 4, 0}, {1, 2, 3, 4}};
std::cout << getMinimumIndex(a); // 4-th vector posseses the value '0'
return 0;
}
【问题讨论】:
-
您必须使用
vector的vectors 吗?一个连续的vector并自己处理 1D->2D 映射将使这变得非常简单。 -
您的
vector排序了吗?因为那时您可能会通过修改后的二进制搜索来完成O(log(n))。如果不是,您可能会查看O(n)... -
@user4581301 是的。基本上,它应该存储了一个自定义类。我刚刚提出了一个实现可能算法的案例。但是,我不确定解决方法。
-
如果您的数据没有排序,那么显然您必须扫描所有元素,
-
如果它们被排序,那么每个向量的第一个元素不是该向量中的最低元素吗?我假设您的全局最小值基于相同的比较器。
标签: c++ algorithm c++11 stdvector