本题中主要使用了set的特性,即set中的内容不会重复,由此利用set存储所有三个数字的和,再通过将set转换为list(set是不可以进行排序取值的,只可添加,所以需要进行数据类型转换),利用list的sort方法,对所有的和进行从大到小的排序,最后输出第三位,即使本题结果。
package lanqiao;
import java.util.*;
/**
* 2024/03/21
*/
public class lanqiao_第三大的和 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
int[] arr = new int[n];
for (int i = 0; i < n; i++)
arr[i] = scan.nextInt();
Set<Integer> set = new HashSet<>();
for (int i = 0; i < n; i++) {
for (int j = 0; j < i; j++) {
for (int k = 0; k < j; k++) {
int res = arr[i] + arr[j] + arr[k];
set.add(res);
}
}
}
List<Integer> list = new ArrayList<>(set);
list.sort((o1, o2) -> o2 - o1);
// for (int i=0;i<list.size();i++)
// System.out.print(list.get(i)+" ");
System.out.println("该数组第三大的和为:"+list.get(2));
}
}
5
5 2 4 3 1
该数组第三大的和为:10
Process finished with exit code 0