首页 > 解决方案 > 排序集中的最大连续数

问题描述

我有一个SortedSet<int>整数,并且数字以随机顺序添加到其中。例如 1, 2, 4, 0, 3

如何找到从 开始的集合中的最高连续整数0

例如,如果集合包含{1,2,4},结果应该是0

对于{0,1,2},结果应该是2

等等

我确实尝试SortedSet.Max过,但这给了我集合中的最大值,而不是最高的连续值。

标签: c#sortedset

解决方案


您不能使用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。


推荐阅读