我有一个家庭作业练习:编写一个程序,该程序在数组中查找相等元素的最大序列.示例:{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
更多推荐
数组中相等元素的最大序列
发布评论