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

计算模式的算法

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

计算模式的算法

即使您已经有了一些好的答案,我还是决定发布另一个。我不确定它确实增加了很多新内容,但是我不确定它也不是。如果没有其他问题,我敢肯定,它使用的标准标头要比其他任何答案都要多。:-)

#include <vector>#include <algorithm>#include <unordered_map>#include <map>#include <iostream>#include <utility>#include <functional>#include <numeric>int main() {    std::vector<int> inputs{ 1, 1, 1, 1, 2, 2, 2 };    std::unordered_map<int, size_t> counts;    for (int i : inputs)        ++counts[i];    std::multimap<size_t, int, std::greater<size_t> > inv;    for (auto p : counts)        inv.insert(std::make_pair(p.second, p.first));    auto e = inv.upper_bound(inv.begin()->first);    double sum = std::accumulate(inv.begin(),        e,        0.0,        [](double a, std::pair<size_t, int> const &b) {return a + b.second; });    std::cout << sum / std::distance(inv.begin(), e);}

与@Dietmar的答案相比,如果数字中有很多重复,这应该会更快,但是如果数字 大多是 唯一的,他的速度可能会更快。



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

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

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