给定一个未排序的数组,您需要找到数组中o(n) 时间复杂度第二大的元素。 例如:
int[] arr1={7,5,6,1,4,2}; Second largest element in the array : 6
您可以对数组进行排序,然后返回数组中的倒数第二个元素,但这将在 o ( nlogn ) 时间内完成,
算法:
在数组中查找第二大数的 Java 程序: 创建名为的主 Java 类 FindSecondLargestMain.java
FindSecondLargestMain.java
package org.arpit.java2blog; public class FindSecondLargestMain { public static void main(String args[]) { int[] arr1={7,5,6,1,4,2}; int secondHighest=findSecondLargestNumberInTheArray(arr1); System.out.println("Second largest element in the array : "+ secondHighest); } public static int findSecondLargestNumberInTheArray(int array[]) { // Initialize these to the smallest value possible int highest = Integer.MIN_VALUE; int secondHighest = Integer.MIN_VALUE; // Loop over the array for (int i = 0; i < array.length; i++) { // If current element is greater than highest if (array[i] > highest) { // assign second highest element to highest element secondHighest = highest; // highest element to current element highest = array[i]; } else if (array[i] > secondHighest && array[i]!=highest) // Just replace the second highest secondHighest = array[i]; } // After exiting the loop, secondHighest now represents the second // largest value in the array return secondHighest; } }
当你运行上面的程序时,你会得到以下输出:
Second largest element in the array : 6
这就是如何在数组中找到第二大数字的全部内容。