Python 中 collections.Counter() 的时间复杂度是多少?

编程入门 行业动态 更新时间:2024-10-26 06:29:29
本文介绍了Python 中 collections.Counter() 的时间复杂度是多少?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..
collection.Counter("bcdefffaa")

返回输出:

Counter({'f': 3, 'a': 2, 'c': 1, 'b': 1, 'e': 1, 'd': 1})

由于结果是值的降序排序,这是否意味着构建计数器的成本是 O(nlogn) 而不是 O(n)?

Since the result is in descended sorted order of values, does this mean the cost of building the Counter is O(nlogn) and not O(n)?

另外,Java 中 collections.Counter 的等价物是什么?

Also, what is the equivalent of the collections.Counter in Java?

推荐答案

作为 源代码 显示,Counter 只是 dict 的一个子类.构造它是 O(n),因为它必须迭代输入,但对单个元素的操作仍然是 O(1).

As the source code shows, Counter is just a subclass of dict. Constructing it is O(n), because it has to iterate over the input, but operations on individual elements remain O(1).

还请注意,它不会在内部保留顺序,而是在 __repr__ 方法中按最常见的输出排序.

Note also from that source that it does not keep an order internally, but simply sorts by most common on output, in the __repr__ method.

这篇关于Python 中 collections.Counter() 的时间复杂度是多少?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

更多推荐

[db:关键词]

本文发布于:2023-04-30 12:07:23,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1393528.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:复杂度   时间   Python   collections   Counter

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!