找到一些功能的Big-O
Find the Big-O of some functions
嘿,我很难找到这个函数有什么 Big-O,有人能帮帮我吗?,你能解释一下你是如何解决的吗?,谢谢大家(:
public static Node<Polinom> SumPolinoms(Node<Polinom> polinom1, Node<Polinom> polinom2) // 2.B
{
Node<Polinom> temp1, temp2, result, first;
temp1 = polinom1;
temp2 = polinom2;
first = result = new Node<Polinom>(new Polinom(0, 0));
while (temp1 != null && temp2 != null)
{
if (temp1.GetValue().GetPower() == temp2.GetValue().GetPower())
{
result.SetNext(new Node<Polinom>(new Polinom(temp1.GetValue().GetFactor() + temp2.GetValue().GetFactor(), temp1.GetValue().GetPower())));
temp1 = temp1.GetNext();
temp2 = temp2.GetNext();
}
else if (temp1.GetValue().GetPower() < temp2.GetValue().GetPower())
{
result.SetNext(new Node<Polinom>(temp2.GetValue()));
temp2 = temp2.GetNext();
}
else
{
result.SetNext(new Node<Polinom>(temp1.GetValue()));
temp1 = temp1.GetNext();
}
result = result.GetNext();
}
while (temp1 != null)
{
result.SetNext(new Node<Polinom>(temp1.GetValue()));
temp1 = temp1.GetNext();
result = result.GetNext();
}
while (temp2 != null)
{
result.SetNext(new Node<Polinom>(temp2.GetValue()));
temp2 = temp2.GetNext();
result = result.GetNext();
}
return first.GetNext();
}
我可能理解错了代码,但这不会是O(2n)
,因为它只是贯穿temp1
和temp2
的每一项。 O(2n)
简化为 O(n)
。代码也可以大大简化。
嘿,我很难找到这个函数有什么 Big-O,有人能帮帮我吗?,你能解释一下你是如何解决的吗?,谢谢大家(:
public static Node<Polinom> SumPolinoms(Node<Polinom> polinom1, Node<Polinom> polinom2) // 2.B
{
Node<Polinom> temp1, temp2, result, first;
temp1 = polinom1;
temp2 = polinom2;
first = result = new Node<Polinom>(new Polinom(0, 0));
while (temp1 != null && temp2 != null)
{
if (temp1.GetValue().GetPower() == temp2.GetValue().GetPower())
{
result.SetNext(new Node<Polinom>(new Polinom(temp1.GetValue().GetFactor() + temp2.GetValue().GetFactor(), temp1.GetValue().GetPower())));
temp1 = temp1.GetNext();
temp2 = temp2.GetNext();
}
else if (temp1.GetValue().GetPower() < temp2.GetValue().GetPower())
{
result.SetNext(new Node<Polinom>(temp2.GetValue()));
temp2 = temp2.GetNext();
}
else
{
result.SetNext(new Node<Polinom>(temp1.GetValue()));
temp1 = temp1.GetNext();
}
result = result.GetNext();
}
while (temp1 != null)
{
result.SetNext(new Node<Polinom>(temp1.GetValue()));
temp1 = temp1.GetNext();
result = result.GetNext();
}
while (temp2 != null)
{
result.SetNext(new Node<Polinom>(temp2.GetValue()));
temp2 = temp2.GetNext();
result = result.GetNext();
}
return first.GetNext();
}
我可能理解错了代码,但这不会是O(2n)
,因为它只是贯穿temp1
和temp2
的每一项。 O(2n)
简化为 O(n)
。代码也可以大大简化。