c++ - std::count 的复杂性

标签 c++ stl time-complexity

我在一些在线代码测验网站上有一个复杂性限制,即代码在时间和内存上都不应超过 O(N),其中 N 是 vector A 的大小。我的代码完全是(完整代码):

int foo(int X, const std::vector<int> &A) {
    auto N = A.size();
    auto total_hit = std::count(A.cbegin(), A.cend(), X);
    auto K = N - total_hit;
    if (K < 0 || K >= N){
        return -1;
    }
    return K;
}

我得到了超过时间复杂度的结果。有没有可能而不是他们错了?

最佳答案

根据ref :

Complexity: exactly last - first comparisons / applications of the predicate

他们错了!

cplusplus同意:

Complexity: Linear in the distance between first and last: Compares once each element.


当然,std::cbegin()的复杂性, std::cend()std::vector::size()常数


如果我是你,我会联系网站,将他们链接到这个问题。

关于c++ - std::count 的复杂性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37492190/

相关文章:

c++ - 屈服于 OpenMP 中的其他线程/任务

c++ - 快速可变大小容器 C++

数组函数的 JavaScript 运行时复杂度

algorithm - 回文递归算法的时间复杂度

c++ - 将 QAbstractTableModel 实现与自定义类的 QList 一起使用

C++重新定义现有类的输出流

c++ - v <int> pos(MAX)v <int> tmp是非类类型 ‘__gnu_cxx::__alloc_traits<std::allocator<int>>::value_type {aka int}’ pos [i] .push_back(tmp);

java - 查找缺失数字的时间复杂度 O(n)?

堆栈上的 C++ 实例变量存储为指针

c++ - 标准库/模板容器的 const 语义的经验法则?