【问题标题】:Index of vector containing the global minimum包含全局最小值的向量的索引
【发布时间】: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;
}

【问题讨论】:

  • 您必须使用vectorvectors 吗?一个连续的vector 并自己处理 1D->2D 映射将使这变得非常简单。
  • 您的vector 排序了吗?因为那时您可能会通过修改后的二进制搜索来完成O(log(n))。如果不是,您可能会查看O(n)...
  • @user4581301 是的。基本上,它应该存储了一个自定义类。我刚刚提出了一个实现可能算法的案例。但是,我不确定解决方法。
  • 如果您的数据没有排序,那么显然您必须扫描所有元素,
  • 如果它们被排序,那么每个向量的第一个元素不是该向量中的最低元素吗?我假设您的全局最小值基于相同的比较器。

标签: c++ algorithm c++11 stdvector


【解决方案1】:

由于您的向量和向量内的数字都没有排序,因此您必须检查每个数字是否为最小值。 因此,您会得到 O(n) 的复杂度。

您可以像以前那样使用迭代器,也可以简单地使用 2 个 for 循环并使用 a[i][j] 访问向量(由于缺少迭代器的开销,这应该会稍微快一些)。

另外 - 因为你只有 unsigned int,你可以在找到 0 后立即中断。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-01-26
    • 2015-04-29
    • 2020-05-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多