最大N个数与最小N个数之和
描述
给定一个数组,编写一个函数,来计算他的最大N个数和最小N个数的和,需要对数组进行去重
说明
第一行输入M,M表示数组大小
第二行输入M个数,表示数组内容
第三行输入N表示需要计算的最大最小N的个数
输出描述
输出最大N个数和最小N个数的和
例一:
输入
5
95 88 83 64 100
2
输出
342
说明:最大2个数[100 95] 最小2个数[83 64],输出342
例二:
输入
5
3 2 3 4 2
2
输出
-1
说明:最大两个数是[4 3]最小2个数是[3 2],有重叠输出为-1
法一
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while (sc.hasNext()) {
int num = Integer.parseInt(sc.nextLine());
String[] str = sc.nextLine().split("\\s+");
int target = Integer.parseInt(sc.nextLine());
//建立一个treeset来把数据从小到大储存
TreeSet<Integer> set = new TreeSet<>();
for (int i = 0 ; i < num ; i++) {
set.add(Integer.parseInt(str[i]));
}
//判断是否满足不重叠
if (set.size() < target * 2) {
System.out.println(-1);
return;
}
//建立一个数组。把排序好的数据存储到数组,之后就一前一后取走
Integer[] arr = new Integer[set.size()];
set.toArray(arr);
int sum = 0;
for (int i = 0 ; i < target ; i++) {
sum += arr[i] + arr[arr.length - 1 - i];
}
System.out.println(sum);
}
}
}
1092

被折叠的 条评论
为什么被折叠?



