简体   繁体   English

如何在小于 O(n) 的时间复杂度内检查两个 std::vectors 是否相等

[英]How to check whether two std::vectors are equal in less than O(n) time complexity

We can compare two vector using for loop like this我们可以像这样使用 for 循环比较两个向量

    bool checkEquality(vector<int> &A, vector<int> &B){
         if(A.size() != B.size())
             return false;
         int i=0,j=0;
         while(i<A.size() && j<B.size()){
             if(A[i++] != B[j++])
                 return false;
         return true;
    }

but this take O(n) time if elements in vector is n I want to know is there any better way to check whether two vectors are equal or not但这需要 O(n) 时间如果向量中的元素是 n 我想知道是否有更好的方法来检查两个向量是否相等

and plus what is the time complexity for this code snippet加上这个代码片段的时间复杂度是多少

if(A==B) 
   return true;
else 
   return false;

is the above code works faster than O(n)上面的代码是否比 O(n) 运行得更快

is there any better way to check whether two vectors are equal有没有更好的方法来检查两个向量是否相等

Yes there is: A == B works fine, and is much simpler than your code.是的,有: A == B工作正常,并且比您的代码简单得多。

is A == B faster than O(n) A == B比 O(n) 快吗

No, that would be impossible in the general case.不,在一般情况下这是不可能的。 We can only do better than O(n) if we know something about the data, such as that differences are always found near the beginning or the end.如果我们对数据有所了解,我们只能比 O(n) 做得更好,例如总是在开始或结束时发现差异。

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

相关问题 如何在少于O(n)的时间内在std :: set中选择一个随机元素? - How to select a random element in std::set in less than O(n) time? 时间复杂度为O(n)而不是O(n ^ 2)如何? - How is the time complexity O(n) and not O(n^2)? 时间复杂度(O(n) 怎么样) - Time complexity (How is this O(n)) 创建一个函数,用于检查数组是否具有两个相反的元素,但复杂度低于n ^ 2。 (C ++) - Create a function that checks whether an array has two opposite elements or not for less than n^2 complexity. (C++) 打印二叉树中所有节点的祖先。 我们可以在少于O(n ^ 2)的时间复杂度下做到吗? - Print ancestors of all nodes in a Binary Tree. Can we do it in less than O(n^2) time complexity? 判断两个向量在C ++中是否相等,时间复杂度是多少? - What is the time complexity of judging if two vectors are equal in C++? 如何在小于 O(N) 的时间内解决这个问题? - How to solve this in less than O(N)? 减少两个嵌套for循环的时间复杂度O(N*N) - Reduction of time complexity of two nested for loop O(N*N) 检查两个向量是否相等 - Check if two vectors are equal 如何使用时间复杂度优于O(n ^ 2)的STL向量和STL算法进行左连接? - How to do a left join with STL vector and STL algorithms with time complexity better than O(n^2)?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM