相关疑难解决方法(0)

计算数组元素中不同绝对值的数量

我被问到一个面试问题,以找出阵列元素中不同绝对值的数量.我想出了以下解决方案(在C++中),但是面试官对代码的运行时效率不满意.

  1. 我将理解如何提高此代码的运行时效率的指示?
  2. 另外我如何计算下面代码的效率?该for循环执行A.size()时间.但是我不确定STL的效率std::find(在更糟糕的情况下,它可能是O(n)这样的代码O(n²)吗?

代码是:

int countAbsoluteDistinct ( const std::vector<int> &A ) {
  using namespace std;
  list<int> x;

  vector<int>::const_iterator it;
  for(it = A.begin();it < A.end();it++)
    if(find(x.begin(),x.end(),abs(*it)) == x.end())
      x.push_back(abs(*it));
  return x.size();
}
Run Code Online (Sandbox Code Playgroud)

c++ algorithm performance

8
推荐指数
2
解决办法
1万
查看次数

标签 统计

algorithm ×1

c++ ×1

performance ×1