简体   繁体   English

判断两个向量在C ++中是否相等,时间复杂度是多少?

[英]What is the time complexity of judging if two vectors are equal in C++?

Does it have to compare every element one by one? 是否必须逐一比较每个元素?
In such case it must be O(n) right? 在这种情况下,它必须是O(n)对吗?

It doesn't necessarily compare all the elements. 它不一定会比较所有元素。

If the two vectors are of different lengths, it can return false based only on the difference in length, in constant time. 如果两个向量的长度不同,则只能在恒定时间内基于长度的差异返回false。

Otherwise, yes, it has to compare elements until it encounters a difference (all the elements if the two are equal). 否则,是的,它必须比较元素直到遇到差异(如果两个元素相等,则为所有元素)。

when you want to compare two vectors. 当您要比较两个向量时。

  • They must be the same type, such as both of them are vector, it is not acceptable to compare two different type vectors, such as the comparison between vector and vector 它们必须是相同的类型,例如它们都是向量,所以不能比较两个不同类型的向量,例如vector和vector之间的比较
  • The rules to compare two vectors follow the comparison between two strings, not necessarily to compare all elements. 比较两个向量的规则遵循两个字符串之间的比较,而不必比较所有元素。

Generally, in our program, the size of two vectors should already be given (not a variable as the input size) , in that situation, the comparison between two vectors is O(1) since it must finish the comparison in a fixed time. 通常,在我们的程序中,应该已经给出了两个向量的大小(输入大小不能作为变量) ,在这种情况下,两个向量之间的比较为O(1),因为它必须在固定时间内完成比较。

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

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