题目描述:
给出N个正整数ai(1<=i<=n)支持两种操作(可选择任意操作):
1) 删除两个相同的数,添加这两个数之和
2)删除两个数,添加这两个数中的最大值
已知通过n-1次操作后,只剩下一个数,求这个数的最大值
输入描述:
第一行输入一个整数n(1<=n<=10e5)
第二行输入n个整数ai(1<=n<=10e4)
输出描述:
输出一个整数表示答案。
示例一:
输入:
3
2 2 4
输出:
8
示例二:
输入:
4
1 2 3 4
输出:
4
代码书写
package exercise;
import java.util.*;
public class timu2 {
public static void main(String[] args) {
//输入操作
Scanner cin = new Scanner(System.in);
int line = cin.nextInt();
String string1 = new String(cin.nextLine());
String string = new String(cin.nextLine());
Integer[] a = new Integer[line];
if (string.length() > 0) {
String[] temp = string.split(" ");
for (int j = 0; j < temp.length; j++) {
a[j] = (Integer.parseInt(temp[j]));
}
//1)首先进行排序
//Integer[] a = {1,2,3,3,4};
Arrays.sort(a, Collections.reverseOrder());
//2)比较相邻的数据,如果相同都为x,一个置-1,一个置x*2;
// 如果不相同,则一个置-1,一个置x
int num = 0;
while (a[1] > 0 && num <= a.length*a.length) {
for (int i = 1; i < a.length && a[i] >= 1; i++) {
//响铃的相等
if (a[i - 1] == a[i]) {
a[i - 1] = -1;
a[i] = 2 * a[i];
}
Arrays.sort(a, Collections.reverseOrder());
//System.out.println("a=" + Arrays.toString(a));
num++;
}
}
//3)不存在相邻元素相同了
System.out.println("result=" + a[0]);
}
}
}
总结:
1)首先对输入操作还是不够熟悉:如果前面读取过一个字段,那么后面读取行的时候,会读到一个空行,需要进行跳过,且读行的时候,一定要字符串长度大于0.
2)对于数组和集合之间的删除,排序,修改的操作不够很熟悉,导致书写速度过慢。