栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

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

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

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();}

这种方法仍然有一些运行时损失。随着容器大小的增加,使用单独的容器会产生动态分配的成本。您可以就地执行此操作,而不会造成这种损失,但是对于处于此级别的代码,有时最好使其清晰明了,并让优化器(在编译器中)执行其工作。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/383027.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号