如何在Visual C#中获得数组中第二高的数字?

我有一系列的整数。 我想获得该数组中第二高的数字。 是否有捷径可寻?

试试这个(使用LINQ):

int secondHighest = (from number in numbers orderby number descending select number).Skip(1).First(); 

您可以对数组进行排序并在第二个索引处选择项目,但是下面的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); 

是的,有2个变量(第一个和第二个)通过数组,每次计算你得到的这两个单元格(总是把第一个最高,第二个最高,第二个)一次通过你将得到第二个更高的第二个变种。

您没有指定是否要以最小的复杂性执行此操作。

假设您的数组未排序,请参阅: 如何在O(n)中找到长度为n的未排序数组中的第k个最大元素?

要在未排序的数组中查找第K个最大元素:在O(n)中构建最大堆。 现在从堆中删除k个元素; 每次删除都需要log(n)时间来维护堆。 总时间复杂度= O(n + klogn)

要了解在O(n)中构建最大堆,请参阅二进制堆

 max1=0; max2=0; for( int i=0; i < a.Length; i++) { if (arr[i]> max1) { max2=max1; max1=arr[i]; } else { if (a[i]!= max1) && ( a[i] > max2) max2[i]=arr[i]; } } 

首先获取最大数量,一旦更改最大值,就与第二个高数字进行比较,看是否需要交换。 第二个if语句检查该值是否小于max并且大于第二个最大值。 由于短路,如果第一个条件失败则退出if并跳过

  static void Main(string[] args) { //int[] arr = new int[10] { 9, 4, 6, 2, 11, 100, 53, 23, 72, 81 }; int[] arr = { 1, 8, 4, 5, 12, 2, 5, 6, 7, 1, 90, 100, 56, 8, 34 }; int MaxNum = 0; int SecNum = 0; for (int i = 0; i < arr.Length; i++) { if (arr[i] > MaxNum) { if (MaxNum > SecNum) { SecNum = MaxNum; } MaxNum = arr[i]; } if (arr[i] < MaxNum && arr[i] > SecNum) { SecNum = arr[i]; } } Console.WriteLine("Highest Num: {0}. Second Highest Num {1}.", MaxNum, SecNum); Console.ReadLine(); } 
  int[] myArray = new int[] { 0, 1, 2, 3, 13, 8, 5 }; int num1=0, temp=0; for (int i = 0; i < myArray.Length; i++) { if (myArray[i] >= num1) { num1 = myArray[i]; } else if ((myArray[i] < num1) && (myArray[i] > temp)) { temp = myArray[i]; } } Console.WriteLine("The Largest Number is: " + num1); Console.WriteLine("The Second Highest Number is: " + temp); 
 int[] arr = { 1, 8, 4, 5, 12, 2, 5, 6, 7, 1, 90, 100, 56, 8, 34 }; int first, second; // Assuming the array has at least one element: first = second = arr[0]; for(int i = 1; i < arr.Length; ++i) { if (first < arr[i]) { // 'first' now contains the 2nd largest number encountered thus far: second = first; first = arr[i]; } } MessageBox.Show(second.ToString()); 
  static void Main(string[] args) { int[] myArray = new int[] { 0, 1, 2, 3, 13, 8, 5,12,11,14 }; int num1 = 0, temp = 0; for (int i = 0; i < myArray.Length; i++) { if (myArray[i] >= num1) { temp = num1; num1 = myArray[i]; } else if ((myArray[i] < num1) && (myArray[i] > temp)) { temp = myArray[i]; } } Console.WriteLine("The Largest Number is: " + num1); Console.WriteLine("The Second Highest Number is: " + temp); Console.ReadKey(); }