数组中相等元素的最大序列 [英] maximal sequence of equal elements in an array

查看:64
本文介绍了数组中相等元素的最大序列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个家庭作业练习:编写一个程序,该程序在数组中查找相等元素的最大序列.示例:{2,1,1,2,3,3,2,2,2,1} = {2,2,2}.我想到了:

I have for homework the exercise: Write a program that finds the maximal sequence of equal elements in an array. Example: {2, 1, 1, 2, 3, 3, 2, 2, 2, 1} = {2, 2, 2}. I came up with this:

Console.WriteLine("Enter array lenght");
            int arrLenght = int.Parse(Console.ReadLine());
            int[] arr = new int[arrLenght];
            Console.WriteLine("Enter array elements");
            for (int i = 0; i < arr.Length; i++)
            {
                arr[i] = int.Parse(Console.ReadLine());
            }
            for (int i = 0; i < arr.Length; i++)
            {
                if (arr[i] == arr[i + 1] && arr[i] == arr[i + 2])
                {
                    Console.WriteLine("Maximal sequence of numbers is: {0},{1},{2}",arr[i],arr[i+1],arr[i+2]);
                    break;
                }

            }

这仅在序列正好是3个数字长的情况下有效.我必须搜索数组并找到最大的序列,但我不知道该如何编码.如果问题很傻,我很抱歉,但是我是新手,在其他任何地方都找不到解决方案.谢谢

This works only if the sequence is exactly 3 numbers long. I have to search the array and find the largest sequence but i don't know how to code this. I'm sorry if the question is silly but i am a newbie and i couldn't find solution anywhere else. Thanks

推荐答案

如果您要寻找优雅,请使用Linq

If you are looking for elegance then use Linq

var seq = new int[] {2, 1, 1, 2, 3, 3, 2, 2, 2, 1};

int[] max = seq.Select((n, i) => new { Value = n, Index = i})
    .OrderBy(s => s.Value)
    .Select((o, i) => new { Value = o.Value, Diff = i - o.Index } )
    .GroupBy(s => new { s.Value, s.Diff})
    .OrderByDescending(g => g.Count())
    .First()
    .Select(f => f.Value)
    .ToArray();

这就是为什么我♥Linq

That's why I ♥ Linq

这篇关于数组中相等元素的最大序列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆