如何获取数组中连续≥x次超过y的子序列的最后元素索引?
问题分析与解决方案
你的代码当前会输出7、8、14,原因是它会把同一段连续超阈值序列中所有满足“连续x个元素超过y”的子序列末尾索引都列出来。比如第一个连续块(索引5-8的元素52、50、51、60),当起始索引i=5时,得到末尾索引7;i=6时得到末尾索引8——这两个属于同一个连续超阈值块,你只需要保留该块的最后一个索引。
修正思路
我们需要先识别出所有连续的超阈值元素块,然后对每个块判断其长度是否≥x,若是则取该块的最后一个元素索引。
修正后的代码(循环实现,高效直观)
List<int> series = new List<int>() { 43, 41, 2, 3, 4, 52, 50, 51, 60, 5, 7, 9, 47, 45, 46 }; int y = 40; int x = 3; List<int> result = new List<int>(); int currentStreak = 0; for (int i = 0; i < series.Count; i++) { if (series[i] > y) { currentStreak++; // 当到达序列末尾,或下一个元素不满足条件时,检查当前连续长度 if (i == series.Count - 1 || series[i + 1] <= y) { if (currentStreak >= x) { result.Add(i); } currentStreak = 0; } } else { currentStreak = 0; } } // 输出结果:8、14 foreach (int idx in result) { Console.WriteLine(idx); }
代码说明
- 用
currentStreak跟踪当前连续超过y的元素个数 - 当遇到不满足条件的元素,或者遍历到序列末尾时,检查当前连续长度是否≥x:
- 若是,则将当前索引(该连续块的最后一个元素索引)加入结果列表
- 重置
currentStreak,开始跟踪下一个可能的连续块
另一种Linq实现方式
如果偏好Linq风格,可以通过分组连续元素来实现:
var indexedSeries = series.Select((val, idx) => new { Value = val, Index = idx }); int groupKey = 0; var consecutiveGroups = indexedSeries .GroupBy(item => { if (item.Value <= y) { groupKey++; } return groupKey; }) .Where(g => g.All(item => item.Value > y) && g.Count() >= x); var result = consecutiveGroups.Select(g => g.Last().Index).ToList();
内容的提问来源于stack exchange,提问作者suria suria
相关产品推荐
相关产品推荐

