C# 如何找到不在列表中的第一个正整数

C# 如何找到不在列表中的第一个正整数,c#,algorithm,list,C#,Algorithm,List,假设我有一个数字列表,其中的每一个都是唯一且有序的: List<int> list = new List<int> {0, 1, 3, 4, 9, 10, 15}; 那么新的数字应该是2 您对实现此算法有什么好主意吗,谢谢。只需对列表进行排序,然后检查: var list = new[] { 0, 1, 3, 4, 9, 10, 15 }; var holes = Enumerable.Range(0, list.Max()+2).Except(list).ToLi

假设我有一个数字列表,其中的每一个都是唯一且有序的:

List<int> list = new List<int>
  {0, 1, 3, 4, 9, 10, 15};
那么新的数字应该是2

您对实现此算法有什么好主意吗,谢谢。

只需对列表进行排序,然后检查:

var list = new[] { 0, 1, 3, 4, 9, 10, 15 };
var holes = Enumerable.Range(0, list.Max()+2).Except(list).ToList();
List<int> list = new List<int> {
  0, 1, 3, 4, 9, 10, 15
};

// if the list is ordered, you don't need this
list.Sort();

// if list is dense 
int result = list[list.Count - 1] + 1;

// check for "holes", providing that list values are unique (list[i - 1] != list[i])
for (int i = 1; i < list.Count; ++i)
  if (list[i - 1] + 1 != list[i]) {
    result = list[i - 1] + 1;

    break;
  }

如果我理解正确,您希望找到列表中没有的第一个正整数。因为您使用的是第一个数字,所以我假设您不需要一个包含所有孔的数字数组

这样做的方式是假设数组按示例中的方式排序,只需从零开始,然后添加一,直到数组不包含数字:

int[] arrayWithNumbers = new int[] {0, 1, 3, 4, 9, 10, 15};

int i = 0;
while (arrayWithNumbers.Contains(i)) //check if number already exists in array
{
    i++; //increment by 1
}

Console.WriteLine(i);

你…吗?你的问题是什么?你试过什么?你需要一个变量和一个循环…我按照L0laapk3的建议更改了标题,现在这个标题应该更准确了。谢谢@l0laapk3这里,我做了你的家庭作业。至少解释一下这段代码的作用。这也不能满足OP的第二个要求,当列表为{0,1}时,返回一个超出列表2末尾的洞。我检查了代码,它不仅可以返回第一个要求的洞列表,还可以返回第二个要求。在这种情况下,列表包含1个元素,即2,谢谢。只有一个问题,对于第一个要求,孔列表包含16个,我认为应该删除。谢谢你的回答,你理解正确。但是对于您的代码,我认为应该是:whilearrayWithNumbers.contains没有not-operator.right,对不起。我没有测试就很快把它拼凑起来:我现在改了谢谢,你的答案很简洁,很好。别忘了接受有用的答案;谢谢你的回答,它是正确的
int[] arrayWithNumbers = new int[] {0, 1, 3, 4, 9, 10, 15};

int i = 0;
while (arrayWithNumbers.Contains(i)) //check if number already exists in array
{
    i++; //increment by 1
}

Console.WriteLine(i);