我在我的数组中找到次数最多的问题。事情是,它不适用于我所有的示例。 当我从键盘读取数字后,我把它们放在方法test然后我对它们进行排序..例如:(用户输入)1,2,3,4,5,6,7,8,9,10 exit:10,9,.. 3,2,1 现在我想要显示的第二大数与循环.. **任务是:找到第二大数字,如果可能的话,如果不是CW(“错误”) **在数组中找到第二个最大值
代码评论//这里我不知道如何扭转正确的那部分代码。
我希望我的问题是有道理的......
public static int test(int[] polje)
{
int temp = 0;
Console.WriteLine();
for (int c = 0; c < polje.Length; c++)
{
for (int b = c + 1; b < polje.Length; b++)
{
if (polje[c] > polje[b])
{
temp = polje[c];
polje[c] = polje[b];
polje[b] = temp;
}
}
}
int secondlargest = 0;
//HERE
for (int i = polje.Length - 1; i >= 0; i--)
{
if (polje[polje.Length - 2] == polje[polje.Length - 1] || polje[polje.Length - 2] == 0)
{
Console.WriteLine("Wrong!");
break;
}
else
{
Console.WriteLine("Second largest number is :{0}", polje[polje.Length - 2]);
secondlargest = polje[polje.Length - 2];
break;
}
}
return secondlargest;
}
static void Main(string[] args)
{
int[] polje = new int[10];
Console.WriteLine("Enter values");
for (int i = 0; i < 10; i = i + 1)
{
polje[i] = int.Parse(Console.ReadLine());
if (polje[i] == 0)
{
break;
}
}
test(polje);
Console.ReadLine();
}
}
}
这功课吗?因为你使用List和排序,或者LINQ和OrderByDescending并且用Take(2)来获得两个最大的值。 –
如果你已经对它们进行了排序,第二个循环的重点是什么?根据您是按升序还是降序排序,只要您的数组有两个以上的记录,您可以选择数组的第二个索引或数组的第二个索引。 – RizJa
http://stackoverflow.com/questions/14810444/find-the-second-maximum-number-in-an-array-with-the-smallest-complexity – Damith