简体   繁体   中英

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

    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

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)

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.

is A == B faster than 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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