Java在数组中查找第二大数字
通过对数组进行排序并返回第二大数字,我们可以在Java中找到第二大数字。让我们看一下完整的示例,以找到java数组中的第二大数字。
public class SecondLargestInArrayExample{
public static int getSecondLargest(int[] a, int total){
int temp;
for (int i = 0;i <total;i++) {
for (int j = i + 1;j <total;j++) {
if (a[i] >a[j]) {
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
return a[total-2];
}
public static void main(String args[]){
int a[]={1,2,5,6,3,2};
int b[]={44,66,99,77,33,22,55};
System.out.println("Second Largest: "+getSecondLargest(a,6));
System.out.println("Second Largest: "+getSecondLargest(b,7));
}
}
输出:
Second Largest: 5Second Largest: 77
使用数组查找数组中的第二大数字
让我们看看另一个示例,使用集合来获取Java数组中第二大的元素或数字。
import java.util.Arrays;
public class SecondLargestInArrayExample1{
public static int getSecondLargest(int[] a, int total){
Arrays.sort(a);
return a[total-2];
}
public static void main(String args[]){
int a[]={1,2,5,6,3,2};
int b[]={44,66,99,77,33,22,55};
System.out.println("Second Largest: "+getSecondLargest(a,6));
System.out.println("Second Largest: "+getSecondLargest(b,7));
}
}
输出:
Second Largest: 5Second Largest: 77
使用集合在数组中查找第二大数字
让我们看看另一个示例,使用集合在java数组中获取第二大数字。
import java.util.*;
public class SecondLargestInArrayExample2{
public static int getSecondLargest(Integer[] a, int total){
List<Integer> list=Arrays.asList(a);
Collections.sort(list);
int element=list.get(total-2);
return element;
}
public static void main(String args[]){
Integer a[]={1,2,5,6,3,2};
Integer b[]={44,66,99,77,33,22,55};
System.out.println("Second Largest: "+getSecondLargest(a,6));
System.out.println("Second Largest: "+getSecondLargest(b,7));
}
}
输出:
Second Largest: 5Second Largest: 77