【发布时间】:2018-09-26 15:46:56
【问题描述】:
我在尝试获取列表 (I) 的正确索引时遇到了麻烦。基本上,该算法对连续数字列表进行排序,例如 1、3、5、7、9、13,并返回缺少的数字(在本例中为 11)。我的问题是温度保持在-1,知道为什么吗?据我了解,温度应该随着我的增加而增加
public static int FindMissing(List<int> list)
{
int difference;
int missing = 0;
for (int i = 0; i < list.Count; i++)
{
difference = list[1] - list[0];
int temp = list.IndexOf(i);
if (temp > 0)
{
if (list[i] - list[i - 1] != difference)
{
missing = list[i - 1] + difference;
}
}
}
return missing;
}
Alexandru Popa 给了我一个很好的答案,但是对于以后看这个帖子的人来说,有人向我展示了 continue 关键字,它最终像这样工作
public static int FindMissing(List<int> list)
{
int difference;
int missing = 0;
for (int i = 0; i < list.Count; i++)
{
if (i == 0) continue;
difference = list[1] - list[0];
if (list[i] - list[i - 1] != difference)
{
missing = list[i - 1] + difference;
}
}
return missing;
}
【问题讨论】:
-
如果您提供的列表正确,则 temp 将为-1,0,-1,1,-1,2。您完全确定您提供的信息正确吗?
-
您在寻找IndexOf 索引吗?如果列表是 10 并且从 100 开始怎么办。您不使用差异 = list[1] - list[0];
-
@paparazzo 我正在寻找我正在查看的列表中的当前元素的 IndexOf,所以如果列表元素是 1040,1220,1580,我只想要 if如果我至少在第二个元素上,则要执行的语句。
-
@TozuPug 您需要将其编辑到您的问题中,而不是将其添加为评论。