为什么我的代码在Visual Studio上运行时无法在hackerearth中工作?数组中最常用的元素



下面的代码在visual studio中提供了正确的输出,但在HackerArth中显示错误为System.FormatException:输入字符串的格式不正确和在GFG编译器中未处理的异常:System.IndexOutOfRangeException:索引超出了数组的界限样本输入:5 1 1 1 2,输出:1。这个问题是在HackerArth一维数组中提出的。

using System;
namespace HK
{
class Program
{
static void Main()
{
int size = Convert.ToInt32(Console.ReadLine());
int[] arr = new int[size];
for (int i = 0; i < size; i++)
{
arr[i] = Convert.ToInt32(Console.ReadLine());
}
int element = 0;
int count = 0;
for (int i = 0; i < size; i++)
{
int tempelement = arr[i];
int tempcount = 0;
for (int j = 0; j < size; j++)
{
if (arr[j] == tempelement)
tempcount++;
}
if (tempcount > count)
{
count = tempcount;
element = tempelement;
}
}
Console.WriteLine(element);
Console.ReadLine();
}
}
}

您的代码本身没有问题,但您对问题的理解有问题。

您将获得2个输入。一个是说预期的数字,另一个是一个包含实际数字的字符串。

现在,在我发布一个可能的解决方案之前,让我给你我个人的看法,为什么我认为这个特定的挑战或不足是有缺陷的:

计算分数的公式:(max_score(-(代码中的字符数/15.0(

这里鼓励您编写小而紧凑的代码,使用尽可能小的命名空间、类和变量名称,尽可能采用语法快捷方式,并忽略任何非函数字符,如。。。评论。

虽然仍有一些用例会严重限制内存,但我不认为这是当今编程初学者应该担心的问题。

因此,HackerArth提供了一种公认的(不好的(方法。如果这有助于你学习语言,那就由你自己决定。

using System;
using System.Linq;
namespace MostFrequentElement
{
class Programm
{
static void Main(string[] args)
{
//we don't need the first input in our approach, so we discard it
Console.ReadLine();
//read the second line and split it
var number = Console.ReadLine().Split(' ')
//group it by itself
.GroupBy(x => x)
//order descending, by how often a number occured
.OrderByDescending(x => x.Count())
//then break the tie, as per Jeroens comment
.ThenByDescending(x => x.Key)
.First();
Console.WriteLine(number.Key);
}
}
}

为了证明我关于得分的观点:如果你删除所有评论、空白和几乎所有的换行符,你最终会得到:

using System;using System.Linq;
namespace M{class P {static void Main(string[] a){Console.ReadLine();
var n=Console.ReadLine().Split(' ')
.GroupBy(x=>x)
.OrderByDescending(x=>x.Count())
.ThenByDescending(x=>x.Key)
.First();Console.WriteLine(n.Key);}}}

与可读性更强的第一次迭代相比,这将给你16.x分,而第一次迭代只会给你11分。

最新更新