简体   繁体   English

使用 set_union 的两个数组的联合这个代码的时间复杂度是多少?

[英]What is the time complexity of this code Union Of two Arrays using set_union?

#include<iostream>
#include<bits/stdc++.h>

using namespace std;

int main() {
    int t;
    cin >> t;
    while (t--) {
        int n, m;
        cin >> n >> m;
        vector<int> v1(n);
        vector<int> v2(m);
        for (int i = 0; i < n; i++) {
            cin >> v1[i];
        }
        for (int i = 0; i < m; i++) {
            cin >> v2[i];
        }
        set<int> s1(v1.begin(),v1.end());
        set<int> s2(v2.begin(), v2.end());
        set<int> s3;
        set_union(s1.begin(), s1.end(), s2.begin(), s2.end(), inserter(s3, s3.begin()));
        for (auto i : s3) cout << i;
    }
}

This code takes two vectors and unions them?这段代码需要两个向量并将它们联合起来? Eg: if the input is 5,4,3,2,1 and 5,4,6 Output will be 1,2,3,4,5,6例如:如果输入是 5,4,3,2,1 和 5,4,6 输出将是 1,2,3,4,5,6

I am confused about its time complexity?我对它的时间复杂度感到困惑? What is time complexity of creation of a set from a vector?从向量创建集合的时间复杂度是多少? What is time complexity of using set_union function?使用 set_union 函数的时间复杂度是多少?

In your code, you are using std::set 's.在您的代码中,您使用的是std::set In the C++ standard library, unfortunately, std::set 's are ordered (and we have std::unordered_set ).不幸的是,在 C++ 标准库中, std::set有序的(我们有std::unordered_set )。 Thus, most of the "hard work" in your code is actually converting the vectors into ordered sets;因此,代码中的大部分“艰苦工作”实际上是将向量转换为有序集; that takes O(n log(n) + m log(m)) time.这需要 O(n log(n) + m log(m)) 时间。 The union is - almost certainly - linear, as @StPiere suggests, so an additional O(n+m) time.正如@StPiere 所建议的那样,联合几乎可以肯定是线性的,因此需要额外的 O(n+m) 时间。

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

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