代码之家  ›  专栏  ›  技术社区  ›  Remi.b

“x”的所有元素是否都存在于“y”中(排序向量)?

  •  1
  • Remi.b  · 技术社区  · 6 年前

    x y

    A. All elements of `y` are present in `x`
    B. Some but not all elements of `y` are present in `x`
    C. No element of `y` is present in `x`
    U. Undefined (because `y` is empty)
    

    实现这一点的一个简单方法是

    template<typename T>
    char f(std::vector<T> x, std::vector<T> y)
    {
        if (y.size() == 0)
        {
            return 'U';
        }
    
        bool whereAnyElementFound = false;
        bool whereAnyElementNotFound = false;
        for (T& y_element : y)
        {
            bool isElementFound = std::find(x.begin(),x.end(),y_element) != x.end();
            if (isElementFound)
            {
                whereAnyElementFound = true;
                if (whereAnyElementNotFound)
                {
                    return 'B';
                }
            } else
            {
                whereAnyElementNotFound = true;
                if (whereAnyElementFound)
                {
                    return 'B';
                }
            }
        }
        if (whereAnyElementFound)
        {
            return 'A';
        } else if (whereAnyElementNotFound)
        {
            return 'C';
        }
        abort();
    }
    

    inputs: x = {1,2,4,5} y = {2,5}
    output: A
    
    inputs: x = {1,2,4,5} y = {2,7}
    output: B
    
    inputs: x = {1,2,4,5} y = {6,7}
    output: C
    
    inputs: x = {1,2,4,5} y = {}
    output: U
    

    然而,该方法没有利用两个向量都被排序的事实。对于较大的向量,如何使此函数更快?

    1 回复  |  直到 6 年前
        1
  •  4
  •   NathanOliver    6 年前

    为了支付 O(N) 您可以使用的额外空间 std::set_intersection O(2(N1+N2-1)) 并生成两个向量之间所有公共元素的“集合”。然后可以检查新“set”的大小来计算A、B、C和U。

    int main()
    {
        std::vector<int> v1{1,2,3,4,5,6,7,8};
        std::vector<int> v2{5,7,9,10};
    
        std::vector<int> intersection;
    
        std::set_intersection(v1.begin(), v1.end(),
                              v2.begin(), v2.end(),
                              std::back_inserter(intersection));
        if (intersection.size() == v2.size() && v2.size() > 0)
            std::cout << "A";
        else if (intersection.size() > 0)
            std::cout << "B";
        else if (intersection.size() == 0 && v2.size() > 0)
            std::cout << "C";
        else
            std::cout << "U";
    }