std::find()是线性的(O(n))。我将使用排序的关联容器来处理此问题,特别是std ::
set。
#include <vector>#include <set>using namespace std;int distict_abs(const vector<int>& v){ std::set<int> distinct_container; for(auto curr_int = v.begin(), end = v.end(); // no need to call v.end() multiple times curr_int != end; ++curr_int) { // std::set only allows single entries // since that is what we want, we don't care that this fails // if the second (or more) of the same value is attempted to // be inserted. distinct_container.insert(abs(*curr_int)); } return distinct_container.size();}这种方法仍然有一些运行时损失。随着容器大小的增加,使用单独的容器会产生动态分配的成本。您可以就地执行此操作,而不会造成这种损失,但是对于处于此级别的代码,有时最好使其清晰明了,并让优化器(在编译器中)执行其工作。



