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

二维数组遍历:查找连续超温最长时段的行索引问题

问题:找出温度连续超阈值最长时段的行索引

需要遍历二维数组,找出温度连续高于给定阈值K的最长时段所在的行索引,规则如下:

  • 若存在多个符合条件的行,返回索引最小的行
  • 若无符合条件的行,返回-1

示例输入

11 10 30
1 2 3 4 5 6 7 8 9 10
34 34 30 10 34 34 10 10 10 10
35 35 35 3 35 35 3 3 3 3
11 11 11 11 11 11 11 11 11 11
1 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 39 4 5 6 7 8 9 10
3 3 3 3 3 3 35 35 35 35

注:11是行数(定居点数量),10是列数(天数),30是温度阈值

示例输出

11


现有代码问题分析

当前代码逻辑错误:统计的是每行中所有高于阈值的温度总个数,而非连续高于阈值的最长时段长度。比如示例中第4行(索引3)所有高于30的温度有10个,导致代码返回3,但实际最长连续时段是第11行(索引10)的连续4个35,正确结果应为11。


修正后的代码

using System;
internal class Program
{
    private static void Main(string[] args)
    {
        string input = Console.ReadLine();
        string[] firstLine = input.Split(" ");
        int cntSettlements = Convert.ToInt32(firstLine[0]);
        int cntDay = Convert.ToInt32(firstLine[1]);
        int tempLimit = Convert.ToInt32(firstLine[2]);

        int[,] dataIn = new int[cntSettlements, cntDay];

        for (int i = 0; i < cntSettlements; i++)
        {
            string input1 = Console.ReadLine();
            string[] rowData = input1.Split(" ");
            for (int j = 0; j < cntDay; j++)
            {
                dataIn[i, j] = Convert.ToInt32(rowData[j]);
            }
        }

        int longestContinuousLength = 0;
        int targetRowIndex = -1;

        for (int i = 0; i < cntSettlements; i++)
        {
            int currentContinuous = 0;
            int maxInRow = 0;

            for (int j = 0; j < cntDay; j++)
            {
                if (dataIn[i, j] > tempLimit)
                {
                    currentContinuous++;
                    if (currentContinuous > maxInRow)
                    {
                        maxInRow = currentContinuous;
                    }
                }
                else
                {
                    currentContinuous = 0;
                }
            }

            if (maxInRow > longestContinuousLength)
            {
                longestContinuousLength = maxInRow;
                targetRowIndex = i + 1;
            }
        }

        Console.WriteLine(targetRowIndex);
    }
}

代码说明

  1. 遍历每行时,用currentContinuous记录当前连续超阈值的天数,maxInRow记录该行的最长连续时段长度
  2. 温度不达标时,立即重置currentContinuous为0
  3. 每行遍历结束后,仅当该行最长连续长度大于全局最长时,才更新结果(保证出现相同长度时保留索引最小的行)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 18:45:38