C++ 包含全局最小值的向量索引
给定一个向量,有没有最佳方法来确定保持全局最小值的向量的索引? 大O表示法的复杂性是什么C++ 包含全局最小值的向量索引,c++,algorithm,c++11,stdvector,C++,Algorithm,C++11,Stdvector,给定一个向量,有没有最佳方法来确定保持全局最小值的向量的索引? 大O表示法的复杂性是什么 #include <algorithm> #include <iostream> #include <vector> unsigned getMinimumIndex(std::vector<std::vector<unsigned>> const& a) { if (!a.size()) return 0; unsi
#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;
}
#包括
#包括
#包括
无符号getMinimumIndex(标准::向量常量&a){
如果(!a.size())
返回0;
unsigned ret=0;unsigned temp;unsigned global=1由于向量和向量中的数字都未排序,因此必须检查每个数字是否为最小值。
因此,得到的复杂性为O(n)
您可以像以前一样使用迭代器,也可以简单地使用2 for循环,并使用[i][j]访问向量(由于迭代器缺少开销,速度应该会稍微快一些)
此外-由于你只有无符号整数,你可以在找到0后立即中断。你必须使用向量的向量吗?一个连续的向量并自己处理1D->2D映射会使这变得非常简单。你的向量排序了吗?因为那样你可能会得到O(log(n))
使用修改过的二进制搜索。如果不是,您可能会看到O(n)
…@user4581301是的。基本上,它应该存储一个自定义类。我刚刚介绍了一个可能实现算法的案例。但是,我不确定解决方法。如果您的数据没有排序,那么显然您必须扫描所有元素,如果已排序,那么每个向量的第一个元素不是该向量中最低的吗?我假设你的全局最小值是基于相同的比较器。