Efficient algorithm to find first available name

前端 未结 7 1342
野性不改
野性不改 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 03:52

    You can certainly do it in O(N) time, N being the number of items in your array:

    • One of "Item 1", "Item 2", ... "Item N+1" must be free, so create an array of N+1 flags.
    • Traverse the items, and for each name if it is of form "Item k" with 0 < k <= N+1, set that flag.
    • Scan the flag array for the first clear flag.

    Additional memory requirement is N+1 bits, which certainly beats any data structure that actually stores all N names.

提交回复
热议问题