You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在C#中获取数组中≥指定阈值的最长连续元素个数

C# 实现连续符合阈值元素的最长长度计算

以下是实现该功能的C#代码,逻辑简洁高效,时间复杂度为O(n)(仅需遍历数组一次):

using System;

class Program
{
    static void Main()
    {
        int[] tempList = { 20, 22, 23, 21, 19, 18, 20, 22, 23, 23, 24, 22, 21 };
        int threshold = 22;
        int maxLength = 0;
        int currentLength = 0;

        foreach (int num in tempList)
        {
            if (num >= threshold)
            {
                currentLength++;
                if (currentLength > maxLength)
                {
                    maxLength = currentLength;
                }
            }
            else
            {
                currentLength = 0;
            }
        }

        Console.WriteLine($"最长连续符合条件的元素长度为: {maxLength}");
        // 输出结果为5,与示例预期一致
    }
}

代码逻辑说明:

  • currentLength:记录当前连续符合条件(>=阈值)的元素个数,遇到不符合条件的元素时重置为0。
  • maxLength:全程跟踪遍历过程中出现过的最长连续序列长度,每次currentLength更新时都进行比较并更新最大值。
  • 遍历数组一次即可完成计算,无需额外空间,是最优的解法之一。

内容的提问来源于stack exchange,提问作者mama

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 00:41:59