基本上我需要在数组中找到第二个最大数字。
假设数组的大小是5
,元素是用户输入的。这是我的解决方案:
class Main {
public static void main(String[] args) {
int q = 0;
Scanner sc = new Scanner(System.in);
int[] arr = new int[5];
for (int i = 0; i < 5; i++) {
arr[i] = sc.nextInt();
}
System.out.println(getSecondLargest(arr, 5));
}
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]) {
return a[i];
}
if (a[i] > a[j]) {
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
return a[total - 2];
}
}
Run Code Online (Sandbox Code Playgroud)
一切正常,但当输入具有最大数量的多个重复值时它会失败。例如 -5 5 5 4 3
它需要4
作为输出给出,但它5
作为输出返回。
我还尝试简化代码,因为已经提到了大小:
import java.util.Arrays;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
int q = 0;
Scanner sc = new Scanner(System.in);
int[] arr = new int[5];
for (int i = 0; i < 5; i++) {
arr[i] = sc.nextInt();
}
print2largest(arr, 5);
}
static void print2largest(int arr[], 5) {
Arrays.sort(arr);
System.out.println(arr[3]);
}
}
Run Code Online (Sandbox Code Playgroud)
但是要使上述简化代码完美运行,数组中必须不存在重复值。
如果有多个重复值,如何获得第二个最大元素。
您可以使用 Java-Stream 来执行此操作:
int[] arr = new int[] {3,5, 9, 7, 4, 12};
int secondLargest = Arrays.stream(arr)
.boxed()
.distinct() // remove duplicates
.sorted(Comparator.comparingInt(value -> (int) value).reversed())
.skip(1) // skip the first largest
.findFirst()
.get();
System.out.println(secondLargest);
Run Code Online (Sandbox Code Playgroud)
输出:
9
Run Code Online (Sandbox Code Playgroud)