[英]How to select a random element in std::set in less than O(n) time?
[英]How to check whether two std::vectors are equal in less than O(n) time complexity
我们可以像这样使用 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;
}
但这需要 O(n) 时间如果向量中的元素是 n 我想知道是否有更好的方法来检查两个向量是否相等
加上这个代码片段的时间复杂度是多少
if(A==B)
return true;
else
return false;
上面的代码是否比 O(n) 运行得更快
有没有更好的方法来检查两个向量是否相等
是的,有: A == B
工作正常,并且比您的代码简单得多。
A == B
比 O(n) 快吗
不,在一般情况下这是不可能的。 如果我们对数据有所了解,我们只能比 O(n) 做得更好,例如总是在开始或结束时发现差异。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.