[英]How to add last element to list in for loop
I am given a list of numbers and I need to find the largest sequence of increasing elements and print it out on the console. 我得到了一个数字列表,我需要找到最大的递增元素序列并将其打印在控制台上。 If there are 2 sequences with equal length then I should print the one that's first from the left.
如果有两个长度相等的序列,那么我应该从左边开始打印第一个序列。
This is what I tried: 这是我尝试的:
for (int i = 0; i < numbers.Count - 1; i++)
{
if (numbers[i] < numbers[i+1] && numbers[i] > 0)
{
counterFirstSequence++;
firstSequence.Add(numbers[i]);
}
}
However, because i only goes to numbers.Count - 1
the very last element never gets added. 但是,因为我只使用
numbers.Count - 1
所以永远不会添加最后一个元素。
for (int i = 0; i < numbers.Count - 1; i++)
{
if (numbers[i] <= 0) continue;
if (numbers[i] >= numbers[i+1]) continue;
counterFirstSequence++;
firstSequence.Add(numbers[i]);
//if the second to last element on the list meets the condition then the last
//element is also valid
//for a zero based index, the second to last element would have the index
//numbers.Count - 2
if(i == numbers.Count - 2)
{
counterFirstSequence++;
firstSequence.Add(numbers[i + 1]);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.