这个大的O标记对这个C ++代码正确吗? [英] Is this big O notation correct for this c++ code?
本文介绍了这个大的O标记对这个C ++代码正确吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
目前,我的最佳情况为o(n),最糟糕的情况为o(n).我不确定以下代码段是否正确,如果有人可以确认它正确或解释错误的原因,我将不胜感激.谢谢!
currently I have best case as o(n), worst case as o(n). I am unsure if this is correct for the following code segment and I would really appreciate if someone could confirm it is correct, or explain why it's wrong. Thanks!
template<typename T>
void vector_print(const T& vector, bool repeat)
{
for (typename T::size_type i = 0; i < vector.size(); ++i)
{
for (typename T::size_type j = 0; j < vector.size(); ++j)
{
std::cout << vector[j] << ",";
}
std::cout << std::endl;
if (!repeat) {
break;
}
repeat = !repeat;
}
}
推荐答案
外部循环永远不会执行两次以上,因此您已经得到 O(2 * vector.size())
,减少为 O(vector.size())
.
The outer loop is never going to be executed more than twice, so you've got O(2*vector.size())
, which reduces to O(vector.size())
.
所以您的回答对我来说似乎是正确的.
So your answer seems correct to me.
这篇关于这个大的O标记对这个C ++代码正确吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文