Determining the first available value in a list of integers

后端 未结 2 551
说谎
说谎 2021-01-02 03:36

I got a simple List of ints.

List myInts = new List();

myInts.Add(0);
myInts.Add(1);
myInts.Add(4);
myInts.Add(6);
myInts.Add(24);
         


        
2条回答
  •  渐次进展
    2021-01-02 04:05

    You basically want the first element from the sequence 0..int.MaxValue that is not contained in myInts:

    int? firstAvailable = Enumerable.Range(0, int.MaxValue)
                                    .Except(myInts)
                                    .FirstOrDefault();
    

    Edit in response to comment:

    There is no performance penalty here to iterate up to int.MaxValue. What Linq is going to to internally is create a hashtable for myInts and then begin iterating over the sequence created by Enumerable.Range() - once the first item not contained in the hashtable is found that integer is yielded by the Except() method and returned by FirstOrDefault() - after which the iteration stops. This means the overall effort is O(n) for creating the hashtable and then worst case O(n) for iterating over the sequence where n is the number of integers in myInts.

    For more on Except() see i.e. Jon Skeet's EduLinq series: Reimplementing LINQ to Objects: Part 17 - Except

提交回复
热议问题