Java程序找到数组中的第二大数字
时间:2020-02-23 14:34:12 来源:igfitidea点击:
在本教程中,我们将看到如何在数组中找到第二大数字。
问题 :
鉴于未蚀刻的数组,我们需要在数组中找到第二大元素
o(n)时间复杂性。
例如:
int [] arr1 = {7,5,6,1,4,2};阵列中的第二大元素:6
解决方案:
我们可以对数组进行排序,然后返回数组中的第二个最后一个元素,但它将在O(NLogn)时间内完成,
算法:
- 以最小可能的值初始化最高和最终点。
- 迭代阵列。
- 如果当前元素大于最高值
- 分配extwhighest =最高
- 分配最高= CurrentElement
- 否则,如果当前元素大于最终点
- 分配第二个最终元素。
Java程序找到阵列中的第二大数字:
创建名为的主java类 FindSecondLargestMain.java
package org.igi.theitroad;
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;
}
}
运行上面的程序时,我们将得到以下输出:
阵列中的第二大元素:6

