Determining the first available value in a list of integers

后端 未结 2 530
说谎
说谎 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:22

    Well, if the list is ordered from smallest to largest and contains values from 0 to positive infinity, you could simply access the i-th element. if (myInts[i] != i) return i; which would be essentially the same, but doesn't necessitate iterating through the list for each and every Contains check (the Contains method iterates through the list, turning your algorithm into an O(n-squared) rather than O(n)).

提交回复
热议问题