【问题标题】:How to find the first positive integer number that is not in the list [closed]如何找到不在列表中的第一个正整数[关闭]
【发布时间】:2015-11-25 08:41:09
【问题描述】:

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

List<int> list = new List<int>
  {0, 1, 3, 4, 9, 10, 15};

然后我想添加一个新的数字,这个数字必须是唯一的,它的值应该是可以插入到列表的“洞”中的最小值。

在这种情况下,第一个新数字应该是 2,然后是 5,然后是 6,...。

另一个例子,如果列表是:

{0, 1}

那么新的数字应该是2

你有什么好主意来实现这个算法,谢谢。

【问题讨论】:

  • 吗?你的问题是什么?你试过什么?你需要一个变量和一个循环...
  • 我按照 L0laapk3 的建议更改了标题,现在这个标题应该更准确。谢谢@L0laapk3

标签: c# algorithm list


【解决方案1】:

如果我理解正确,您想找到不在列表中的第一个正整数。 (由于您使用的是“第一个”数字,我假设您不需要所有孔的数字数组。)

您这样做的方式是(假设数组的排序方式与您的示例中一样)是简单地从零开始并加一,直到数组不包含数字:

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);

【讨论】:

  • 感谢您的回答,您理解正确。但是对于您的代码,我认为应该是:while (arrayWithNumbers.Contains(i)) without not-operator.
  • 对,对不起。我很快就把它放在一起没有测试它:) 我现在改变了它
  • 谢谢,你的回答很简洁。
  • 不要忘记接受有用的答案;)
【解决方案2】:

只需排序列表然后检查:

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;
  }

【讨论】:

  • 感谢您的回答,正确
【解决方案3】:
var list = new[] { 0, 1, 3, 4, 9, 10, 15 };
var holes = Enumerable.Range(0, list.Max()+2).Except(list).ToList();

【讨论】:

  • “在这里,我完成了你的作业”。至少解释一下这段代码的作用。这也不会满足 OP 的第二个要求,即在列表末尾返回一个孔(当列表为 {0, 1} 时为 2)。
  • 我检查了代码,它不仅可以返回第一个要求的孔列表,还可以返回第二个要求(在这种情况下,列表包含 1 个元素,即 2),谢谢。只有一个问题,对于第一个需求,洞列表包含16个,我觉得应该去掉。
猜你喜欢
  • 2018-04-11
  • 2016-01-16
  • 1970-01-01
  • 1970-01-01
  • 2013-02-12
  • 1970-01-01
  • 2022-12-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多