数组中相等元素的最大序列

编程入门 行业动态 更新时间:2024-10-28 11:22:36
本文介绍了数组中相等元素的最大序列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

更多推荐

数组中相等元素的最大序列

本文发布于:2023-11-29 18:07:18,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1647194.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:序列   组中   元素

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!