编程语言
首页 > 编程语言> > c# – 快速查找SortedDictionary中第一个未使用的密钥?

c# – 快速查找SortedDictionary中第一个未使用的密钥?

作者:互联网

如果我有一个SortedDictionary< int,object>,找到当前没有使用的最低密钥的最快方法是什么?显然,我们可以从0-> int.MaxValue迭代一个计数器i并且如果!Keys.Contains(i)就转义,但除非我们很幸运并且第一个备用键恰好在序列的早期,否则这将非常慢钥匙也许甚至一个不同的.NET类已经为我们这样做了?

解决方法:

所以,如果我理解正确,那么键可以是从0到int.MaxValue的任何地方.在这种情况下,你必须找到键序列中的第一个“洞”.

这应该有效地完成工作:

public static int GetFirstUnusedKey<TValue>(SortedDictionary<int, TValue> dict)
{
    if (dict.Comparer != Comparer<int>.Default)
        throw new NotSupportedException("Unsupported comparer");

    using (var enumerator = dict.GetEnumerator())
    {
        if (!enumerator.MoveNext())
            return 0;

        var nextKeyInSequence = enumerator.Current.Key + 1;

        if (nextKeyInSequence < 1)
            throw new InvalidOperationException("The dictionary contains keys less than 0");

        if (nextKeyInSequence != 1)
            return 0;

        while (enumerator.MoveNext())
        {
            var key = enumerator.Current.Key;
            if (key > nextKeyInSequence)
                return nextKeyInSequence;

            ++nextKeyInSequence;
        }

        return nextKeyInSequence;
    }
}

我添加了几项检查以确保前提条件有效.

标签:c,net,key,sorteddictionary
来源: https://codeday.me/bug/20190624/1276095.html