Efficient algorithm to find first available name

前端 未结 7 1341
野性不改
野性不改 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:04

    A logarithmic-time approach, assuming that you never leave "holes" by deleting items:

    // Inverse binary search for the last one.
    int upperBound = 1;
    while(isInUse(upperBound)) upperBound *= 2;
    
    // Standard binary search for the end once we have a ballpark.
    int lowerBound = upperBound / 2;
    while(lowerBound < upperBound - 1)
    {
        int midpoint = (lowerBound + upperBound) / 2;
        if (isInUse(midpoint))
            lowerBound = midpoint;
        else
            upperBound = midpoint;
    }
    return upperBound;
    

    If item numbers can be freed by deleting, nothing short of linear search will work unless you also keep a "free list" and pick from that.

提交回复
热议问题