找到最低的未使用的唯一的ID列表最低、列表、ID

2023-09-11 04:04:21 作者:茶丸软卷

说有一个列表。列表中的每个项目都有一个唯一的ID。

Say there's a list. Each item in the list has a unique id.

List [5, 2, 4, 3, 1]

当我从该列表中删除一个项目,从项目的唯一ID去用它。

When I remove an item from this list, the unique id from the item goes with it.

List [5, 2, 3, 1]

现在说我想其他项目添加到列表中,并给它至少最低的唯一ID。

Now say I want to add another item to the list, and give it the least lowest unique id.

什么是加入新的项目到列表中时,获得最低唯一的ID最简单的方法?

What's the easiest way to get the lowest unique id when adding a new item to the list?

下面的限制,虽然我倒是preFER,如果我删除一个项目时没有相应调整其他项目的唯一ID。

Here's the restriction though: I'd prefer it if I didn't reassign the unique id of another item when deleting an item.

我知道这会很容易找到的唯一ID,如果我重新分配唯一的ID 5独特的ID 4,当我删除4.然后,我可以得到列表的长度(5),并创建具有唯一ID的新项目用该号码。

I realise it would be easy to find the unique id if I reassigned unique id 5 to unique id 4 when I deleted 4. Then I could get the length of the list (5) and creating the new item with the unique id with that number.

那么,有没有一种方式,不涉及整个列表迭代?

So is there another way, that doesn't involve iterating through the entire list?

编辑:

语言是Java,但我想我在寻找一个通用的算法。

Language is java, but I suppose I'm looking for a generic algorithm.

推荐答案

这是易迅的方法是只放在一个优先级队列中删除的ID和随便挑了一张ID从那里,当你插入新的(或使用尺寸()+1第一列表作为标识的当队列为空)。然而,这将需要另一个列表。

An easy fast way is to just put your deleted ids in a priority queue, and just pick the next id from there when you insert new ones (or use size() + 1 of the first list as id when the queue is empty). This would however require another list.