[英]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.