简体   繁体   English

C++ 中 std::map 的运行时复杂度是多少?

[英]What is the runtime complexity of std::map in C++?

I'm still a little confused about what the runtime complexity is of a std::map in C++.对于 C++ 中的std::map的运行时复杂性,我仍然有点困惑。 I know that the first for loop in the algorithm below takes O(N) or linear runtime.我知道下面算法中的第一个 for 循环需要 O(N) 或线性运行时间。 However, the second for loop has another for loop iterating over the map.但是,第二个 for 循环有另一个 for 循环遍历 map。 Does that add anything to the overall runtime complexity?这是否会增加整体运行时的复杂性? In other words, what is the overall runtime complexity of the following algorithm?换句话说,以下算法的整体运行时复杂度是多少? Is it O(N) or O(Nlog(N)) or something else?是 O(N) 还是 O(Nlog(N)) 还是别的什么?

    vector<int> smallerNumbersThanCurrent(vector<int>& nums) {
        
        vector<int> result;
        map<int, int> mp;
        
        for (int i = 0; i < nums.size(); i++) {
            mp[nums[i]]++;
        }
        
        for (int i = 0; i < nums.size(); i++) {
            int numElements = 0;
            for (auto it = mp.begin(); it != mp.end(); it++) {
                if (it->first < nums[i]) numElements += it->second;
            }
            result.push_back(numElements);
        }
        
        return result;
    }

The complexity of a map is that of insertion, deletion, search, etc. But iteration is always linear. map 的复杂性是插入、删除、搜索等。但迭代始终是线性的。

Having two for loops like this inside each other will produce O(N^2) complexity time, be it a map or not, given the n iterations in the inner loop (the size of the map) for each iteration of the outer loop (the size of the vector, which is the same in your code as the size of the map).有两个这样的 for 循环将产生 O(N^2) 复杂时间,无论是 map 与否,给定内循环中的 n 次迭代(映射的大小)对于外循环的每次迭代(矢量的大小,在您的代码中与地图的大小相同)。

Your second for loop runs nums.size() times, so let's call that N. Looks like the map has as many entries as nums, so this contains same N entries.您的第二个 for 循环运行 nums.size() 次,所以我们称之为 N。看起来 map 的条目与 nums 一样多,因此它包含相同的 N 个条目。 The two for loops then of size N is N*N or N^2.那么大小为 N 的两个 for 循环是 N*N 或 N^2。

The begin and end functions invoked by map are constant time because they each have a pointer reference from what I can tell: map 调用的开始和结束函数是常数时间,因为它们每个都有一个指针引用,据我所知:

C++ map.end function documentation C++ map.end function 文档

Note if you do have two for loops, but the outer one is size N and inner one is different size say M, then complexity is M*N, not N^2.请注意,如果您确实有两个 for 循环,但外部的一个大小为 N,而内部的一个大小不同,比如 M,那么复杂度是 M*N,而不是 N^2。 Be careful on that point, but yes if N is same for both loops, then N^2 is runtime.在这一点上要小心,但是如果两个循环的 N 相同,则 N^2 是运行时。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM