查找数组中最长的连续正数系列的长度

时间:2014-02-04 22:38:37

标签: c# arrays c#-4.0

示例:

 2,3,0,1,-5,10,11,12

正数的最大长度为3。

我有代码来检查数组,但是我不知道如何确保int保持长度而不是重新启动,例如序列停止。

3 个答案:

答案 0 :(得分:3)

    int counter = 0;
    int longestCounter = 0;
    for (int i = 0; i < array.Length; i++)
    {
        if (array[i] > 0) counter++;
        else
        {
            if ( counter > longestCounter ) longestCounter = counter;
            counter = 0; 
        }
    }
    if ( counter > longestCounter ) longestCounter = counter;

答案 1 :(得分:1)

只需添加此答案即可。您可以像这样简单地使用for - 循环(非常类似于其他答案,更紧凑):

int longestLen = 0, currentLen = 0;
for(int i = 0; i < array.Length; i++) {
    currentLen = array[i] > 0 ? currentLen + 1 : 0;
    longestLen = Math.Max(currentLen, longestLen);
}
Console.WriteLine(longestLen); // 3

或Linq,像这样:

int longestLen = array.Aggregate(
    new { c = 0, m = 0 }, 
    (x, n) => new { c = n = (n > 0 ? x.c + 1 : 0), m = Math.Max(n, x.m) }, 
    x => x.m);
Console.WriteLine(longestLen); // 3

答案 2 :(得分:0)

// similar to the "Sliding Windows Algorithm" in "Programming Pearls"
int i, current, maxSoFar;

current = 0;
maxSoFar = 0;
for (i = 0; i < a.Length; i++)
{
    if (a[i] > 0)
    {
        current = current + 1;

        if (current > maxSoFar)
        {
            maxSoFar = current;
        }
    } else {
        current = 0;
    }
}