Time Complexity for an algorithm

后端 未结 1 1650
长发绾君心
长发绾君心 2021-01-23 18:57

Am I correct in my explanation when calculating the time complexity of the following algorithm?

  • A HashSet, moduleMarksheetFiles, is being used to add the files

1条回答
  •  无人共我
    2021-01-23 19:59

    No, it's not squared, this is O(nk). (Technically, that means it's also O((nk)²), but we don't care.)

    Your misconception is that it the worst-case performance of HashSet is what counts here. However, even though a hashtable may have worst-case O(n) insertion time (if it needs to rehash every element), its amortized insertion time is O(1) (assuming your hash function is well behaved; File.GetHashCode presumably is). In other words, if you insert multiple things, so many of them will be O(1) that the occasional O(n) insertion does not matter.

    Therefore, we can treat insertions as constant-time operations, so performance is purely dictated by the number of iterations through the inner loop body, which is O(nk).

    0 讨论(0)
提交回复
热议问题