如何找到最高序列号的最大元素
how to find a max element of highest sequence number
如何找到缺失元素之前的最大序列序号。
input - 123678 output -3
public static void Main()
{
List<int> nums = new List<int>(){1,2,3,6,7,8};
int count = nums.Count;
for(int i=0;i<count;i++){
if((nums[i+1]-nums[i])>1){
Console.WriteLine("Missed Element after digit :" [i]);
}
}
}
fiddle https://dotnetfiddle.net/Hkd0rx
错误
Index was out of range. Must be non-negative and less than the size of
the collection.
您需要跳过最后一个数字,因为它后面没有什么可以比较的。因此,在您的 for
循环中,将条件更改为在 i<count-1
为真时循环。
您的 WriteLine
也有错误。现在它将从特定索引处的字符串 Missed Element after digit :
中选择字符。要正确连接字符串,您可以使用 +
或字符串插值。
List<int> nums = new List<int>() { 1, 2, 3, 6, 7, 8 };
int count = nums.Count;
for (int i = 0; i < count - 1; i++)
{
var current = nums[i];
var next = nums[i + 1];
if ((next - current) > 1)
{
Console.WriteLine("Missing Element(s) between : " + current + " and " + next);
}
}
这里有几个问题:
当 i = 0 .. nums.Count - 1
. 时,nums[i+1]
可能超出范围
- 找到项目后,您应该
break
循环
- 如果所有 项(无遗漏项)按要求顺序排列,您应该return 最后一项。
代码
List<int> nums = new List<int>(){
1, 2, 3, 6, 7, 8
};
// Add sorting if there's no guarantee that num has been sorted
// nums.Sort();
// In case we have no missing item we return the last one
int result = nums[nums.Count - 1];
// Note "nums.Count - 1" instead of "nums.Count"
for (int i = 0; i < nums.Count - 1; ++i)
if (nums[i + 1] - nums[i] > 1) {
result = nums[i];
break; // Note break
}
Console.WriteLine($"Missed Element is after number : {result}");
如何找到缺失元素之前的最大序列序号。
input - 123678 output -3
public static void Main()
{
List<int> nums = new List<int>(){1,2,3,6,7,8};
int count = nums.Count;
for(int i=0;i<count;i++){
if((nums[i+1]-nums[i])>1){
Console.WriteLine("Missed Element after digit :" [i]);
}
}
}
fiddle https://dotnetfiddle.net/Hkd0rx
错误
Index was out of range. Must be non-negative and less than the size of the collection.
您需要跳过最后一个数字,因为它后面没有什么可以比较的。因此,在您的 for
循环中,将条件更改为在 i<count-1
为真时循环。
您的 WriteLine
也有错误。现在它将从特定索引处的字符串 Missed Element after digit :
中选择字符。要正确连接字符串,您可以使用 +
或字符串插值。
List<int> nums = new List<int>() { 1, 2, 3, 6, 7, 8 };
int count = nums.Count;
for (int i = 0; i < count - 1; i++)
{
var current = nums[i];
var next = nums[i + 1];
if ((next - current) > 1)
{
Console.WriteLine("Missing Element(s) between : " + current + " and " + next);
}
}
这里有几个问题:
-
当
nums[i+1]
可能超出范围- 找到项目后,您应该
break
循环 - 如果所有 项(无遗漏项)按要求顺序排列,您应该return 最后一项。
i = 0 .. nums.Count - 1
. 时,代码
List<int> nums = new List<int>(){
1, 2, 3, 6, 7, 8
};
// Add sorting if there's no guarantee that num has been sorted
// nums.Sort();
// In case we have no missing item we return the last one
int result = nums[nums.Count - 1];
// Note "nums.Count - 1" instead of "nums.Count"
for (int i = 0; i < nums.Count - 1; ++i)
if (nums[i + 1] - nums[i] > 1) {
result = nums[i];
break; // Note break
}
Console.WriteLine($"Missed Element is after number : {result}");