我想问一下我的功能的时间复杂性。下面是我用C ++编写的函数。
void List::swap(List& other)
{
List temp;
Iterator r = begin();
Iterator i = other.begin();
while(!i.equals(other.end()))
{
temp.push_back(i.position->data);
i = other.erase(i);
}
while(!r.equals(end()))
{
other.push_back(r.position->data);
r = erase(r);
}
r = temp.begin();
for(r; !r.equals(temp.end()); r.next())
{
push_back(r.position->data);
}
}
功能目的是交换两个链表的元素。练习要求此功能在O(1)时间内执行。因为我使用了3个循环,所以我不确定如何计算我的函数的时间复杂度。
答案 0 :(得分:2)
您可以将增长顺序视为问题复杂性的上限。
第一个while循环是O(other.size())
第二个while循环是O(this.size())
第三个循环是O(other.size())
所以总复杂度是O(2 * other.size()+ this.size()),它更正确地用O表示法描述为O(m + n)或O(n),具体取决于是否大小这两个名单彼此独立。
答案 1 :(得分:1)
由于你在谈论Big Oh表示法,复杂性将是最大值(loop1的复杂性,loop2的复杂性,loop3的复杂性)。由于您使用的是3个循环,因此复杂性绝对不会是O(1)。 提示:由于这些是链表,您只需要交换头指针。