c# - 排序集中的最大连续数
问题描述
我有一个SortedSet<int>
整数,并且数字以随机顺序添加到其中。例如 1, 2, 4, 0, 3
如何找到从 开始的集合中的最高连续整数0
?
例如,如果集合包含{1,2,4}
,结果应该是0
对于{0,1,2}
,结果应该是2
等等
我确实尝试SortedSet.Max
过,但这给了我集合中的最大值,而不是最高的连续值。
解决方案
您不能使用Max()
,因为它将返回集合中的最大值(正如您已经注意到的)。
性能不佳且可能存在错误的示例解决方案,但您明白了:
class Program
{
static void Main(string[] args)
{
//SortedSet will sort elements on its own (since its Sorted...), so we can throw elements at it at random (as in requirements)
var mySet = new SortedSet<int> { -7, -6, -4, -2, -3, -5, -1, 1, 2, 5, 7, 8, 9, 4, 13, 12, 11, 14, 15 };
var yourSet = new SortedSet<int> { 1, 2, 4, 0, 3 };
int mySetCount = CalculateConsecutiveOccurrenceCount(mySet);
int yourSetCount = CalculateConsecutiveOccurrenceCount(yourSet);
Console.WriteLine($"My set: {mySetCount}");
Console.WriteLine($"Your set: {yourSetCount}");
Console.ReadKey();
}
private static int CalculateConsecutiveOccurrenceCount(SortedSet<int> sortedSet)
{
var largestCount = 0;
var consecutiveOccurrenceCount = 0;
var lastRead = (int?)null;
var valuesRead = 0;
using (var enumerator = sortedSet.GetEnumerator())
{
while (enumerator.MoveNext())
{
valuesRead++;
//First item
if (!lastRead.HasValue)
{
lastRead = enumerator.Current;
continue;
}
//Consecutive occurrence
if (enumerator.Current - lastRead == 1)
{
consecutiveOccurrenceCount++;
}
//Consecutive occurrence reset
else
{
//Was it largest consecutive occurence?
if (consecutiveOccurrenceCount > largestCount)
{
//Update then
largestCount = consecutiveOccurrenceCount;
}
//Reset
consecutiveOccurrenceCount = 0;
}
//For last element in enumerable and still have consecutive occurrence - check, if we don't have to update largestCount
if (valuesRead == sortedSet.Count)
{
if (consecutiveOccurrenceCount > largestCount)
{
largestCount = consecutiveOccurrenceCount;
}
}
lastRead = enumerator.Current;
}
}
return largestCount;
}
}
另外,我猜{1,2,4}
应该 yield result == 1
,因为我们连续出现一次:1->2。
推荐阅读
- unix - 如何列出目录中仅包含一个点的所有文件
- c# - 如何在任意网格上找到顶点的邻居?
- javascript - SyntaxError:意外的令牌/在 JSON 中的位置 132
- uml - 课程注册类图
- regex - 检查行是否包含其他行范围内的任何文本
- php - 在 Laravel 中加入 3 个表
- java - Corda 节点未启动并给出错误 初始化失败 errorCode 1gariof
- asp.net-mvc - Pass TempData between Contollers for Modal return Null?
- javascript - 箭头功能不适用于模块?
- c# - 如何在 C# 中读取大文本文件?