Efficient algorithm to find first available name

前端 未结 7 1340
野性不改
野性不改 2021-01-19 03:26

I have an array containing names of items. I want to give the user the option to create items without specifying their name, so my program will have to supply a unique defau

7条回答
  •  不思量自难忘°
    2021-01-19 04:02

    You could try to do the following:

    first:

    • loop through the list, and get all numbered items, this is complexity N
    • for every numbered item, put the item in a tree (in C++: std::map), this is complexity log(N)

    So now you have built up a map with the used numbers, with complexity "N x log(N)"

    Next, iterate to the tree and as soon you see a 'hole', use the number. Worst case is complexity N.

    So in total, the complexity is N x log(N) + N, or simplified: N log(N).

提交回复
热议问题