连续负数算法

时间:2015-02-03 19:38:26

标签: c# algorithm

对于我的生活,我仍然坚持如何跟踪连续负数的最大数量。

我有一个数字列表,可以在for循环的每次迭代中获取类方法。这些数字可以是正面的也可以是负面的,并且没有明确的方法可以知道什么会跟随什么。我需要一个算法,以便它可以实时计算(在循环执行期间)连续的负数。因此,在循环迭代结束时,consecutiveNegative中存储的数字将是一个整数,显示负数最后连续次数后跟另一个负数。

以下是我尝试的内容,但它不起作用......

class Temp
{
    public int consecutiveNegative = 0;
    private bool previousNegative = false;


    public void iterCall(int x)
    {
        if(x > 0)
        {
            if(previousNegative == true)
            {
                consecutiveNegative = 0;
            }
            previousNegative = false;

        }
        else if (x < 0)
        {
            if (previousNegative == false)
            {
                consecutiveNegative = consecutiveNegative + 1;
            }
            previousNegative = true;
        }
    }


}

任何指针?


下面是一些让人们开始搞乱的代码。

Temp classTmp = new Temp();
List<int> nums = new List<int>();
nums.Add(1);
nums.Add(-1);
nums.Add(1);
nums.Add(-1);
nums.Add(-1);
nums.Add(-1);
nums.Add(1);
nums.Add(-1);
nums.Add(-1);
nums.Add(1);

for(int i = 0; i < nums.Count;i++)
{
    classTmp.iterCall(nums[i]);
}
完成循环后,

classTmp.consecutiveNegative应为3。

3 个答案:

答案 0 :(得分:1)

据我了解,代码应修改如下。没有变量来跟踪最大序列,并且不需要存储最后输入的否定性。在任何时候,都可以通过评估

获得所需的结果
Math.Max(ConsecutiveNegative,CurrentConsecutiveNegative)

因为序列可能不会被终止。

class Temp
{
    public int CurrentCosecutiveNegative = 0;
    public int ConsecutiveNegative = 0;

    public void iterCall(int x)
    {
        if(x >= 0)
        {
            ConsecutiveNegative
              = Math.Max(ConsecutiveNegative,CurrentConsecutiveNegative);
            CurrentConsecutiveNegative = 0;
        }
        else
        {
            CurrentConsecutiveNegative++;
        }
    }
}

答案 1 :(得分:1)

您需要maxNegative,以跟踪当前运行时间最长的连续负片。此外,您的x < 0案例中的逻辑错误:第二次是否定的,它不会增加计数。

class Temp
    {
        public int consecutiveNegative = 0;
        public int maxNegative = 0;

        public void iterCall(int x)
        {
            if (x > 0)
            {
                consecutiveNegative = 0;
            }
            else if (x < 0)
            {
                consecutiveNegative += 1;
                if (maxNegative < consecutiveNegative)
                    maxNegative = consecutiveNegative;
            }
        }
    }

正如@Codor所示,使用这种方法,您不需要布尔值来跟踪之前的数字,因为consecutiveNegative将自动重置。

答案 2 :(得分:1)

对于最大的负序列,您需要2个变量,对于当前序列长度,需要另一个变量:

class Temp
{
    public int consecutiveNegative = 0;
    public int curConsecutiveNegatives = 0;

    public void iterCall(int x)
    {
        if (x < 0)
            consecutiveNegative = Math.Max(consecutiveNegative, ++curConsecutiveNegatives);
        else
            curConsecutiveNegatives = 0;

    }
}