发现第二最大数目在具有最小复杂性的阵列 [英] Find the second maximum number in an array with the smallest complexity

查看:105
本文介绍了发现第二最大数目在具有最小复杂性的阵列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

试过用Google搜索,但没有运气。 我如何才能找到与最小复杂性的一个数组中的第二最大数目

Tried to googled it but with no luck. How can I find the second maximum number in an array with the smallest complexity?

code或想法将是多大的帮助。

code OR idea will be much help.

我可以遍历数组并查找最大数量 在那之后,我的最大数量,然后循环阵列再次找到第二方法相同。

I can loop through an array and look for the maximum number after that, I have the maximum number and then loop the array again to find the second the same way.

但可以肯定它是没有效率。

But for sure it is not efficient.

推荐答案

<一个href="http://stackoverflow.com/questions/1811846/how-to-get-the-second-highest-number-in-an-array-in-visual-c">You可以对数组进行排序,然后选择第二个索引处的项目,但以下为O(n)循环就会快得多。

int[] myArray = new int[] { 0, 1, 2, 3, 13, 8, 5 };
int largest = int.MinValue;
int second = int.MinValue;
foreach (int i in myArray)
{
 if (i > largest)
 {
  second = largest;
  largest = i;
 }
else if (i > second)
    second = i;
}

System.Console.WriteLine(second);

试试这个(使用LINQ):

Try this (using LINQ):

int secondHighest = (from number in test
                             orderby number descending
                             select number).Distinct().Skip(1).First()

<一个href="http://stackoverflow.com/questions/1811846/how-to-get-the-second-highest-number-in-an-array-in-visual-c">How获得在Visual C#中的数组的第二高多少?

这篇关于发现第二最大数目在具有最小复杂性的阵列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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