RB树插入循环内的时间复杂度

时间:2016-09-11 10:51:39

标签: c algorithm time-complexity big-o

我对如何计算以下情况的时间复杂性表示怀疑:

我有一串字符。我想要做的是循环所有字符,并为每个字符在RB树中插入一个新节点。

这是代码:

    int length = strlen(myString);
    for(i=0; i<length; i++)
        insertNodeInTree(myString[i]);

现在,循环之前树是空的,我知道RB-Tree插入的时间复杂度是O(log N),树中有N个节点。

在这种情况下,树内的节点数量线性地取决于我的索引i的值。当i = 0(第一个元素)时,树中没有节点,当i = n时,树中有n个节点。

所以我的问题是:这段代码的时间复杂度是多少?

我在考虑O(W * log W),其中W是字符串的长度,但我认为这是非常错误的。 然后我认为每次迭代的复杂性可能是:

O(log 1) + O(log 2) + .... + O(log W-1) + O(log W) = O(log W!)

但我不确定这是否正确......

1 个答案:

答案 0 :(得分:1)

给定代码段的时间复杂度

Enter

T(N)= T1(N)+ T2(N)-------(1)

if (2 and 1) in dice_counter: print('Two pair +5pts') elif (3 and 1) in dice_counter: print('Three of a kind +10pts') elif (3 and 2) in dice_counter: print('Full house +15pts') elif (4 and 1) in dice_counter: print('Four of a kind +20pts') elif dice_counter == [0,0,1,1,1,1,1] or [0,1,1,1,1,1,0]: print('Straight +20pts') elif 5 in dice_counter: print('Five of a kind +30pts') else: break

int length = strlen(myString); for(i=0; i<length; i++) insertNodeInTree(myString[i]);

T1(N) = O(n)  // For calculating the  Length of the string

现在T2(N)在O(nlog(n))

因此T(N)是O(nlog(n))