题解 | #合并表记录#
合并表记录
https://www.nowcoder.com/practice/de044e89123f4a7482bd2b214a685201
import java.util.Scanner;
import java.util.ArrayList;
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
// 注意 hasNext 和 hasNextLine 的区别
while (in.hasNextLine()) { // 注意 while 处理多个 case
int length = Integer.valueOf(in.nextLine());
ArrayList<Integer> arrlIndex = new ArrayList<Integer>();
ArrayList<Integer> arrlValue = new ArrayList<Integer>();
// System.out.println(length);
for (int i = 0; i < length; i++) {
String twoNum = in.nextLine();
int index = Integer.valueOf(twoNum.split(" ")[0]);
int value = Integer.valueOf(twoNum.split(" ")[1]);
if (arrlIndex.size() == 0) {
arrlIndex.add(index);
arrlValue.add(value);
//System.out.println('a');
} else {
for (int j = 0; j < arrlIndex.size(); j++) {
if (index == arrlIndex.get(j)) {
arrlValue.set(j, arrlValue.get(j) + value);
//System.out.println('b');
break;
} else if (j == arrlIndex.size() - 1) {
arrlIndex.add(index);
arrlValue.add(value);
break;
} else {
continue;
}
}
}
}
int length2 = arrlIndex.size();
//System.out.println(length2);
for (int i = 0; i < length2 - 1; i++) {
for(int j =0;j<length2-1;j++){
int tempNum = 0;
int tempNum2 = 0;
if (arrlIndex.get(j) > arrlIndex.get(j + 1)) {
tempNum = arrlIndex.get(j);
arrlIndex.set(j, arrlIndex.get(j + 1));
arrlIndex.set(j + 1, tempNum);
tempNum2 = arrlValue.get(j);
arrlValue.set(j, arrlValue.get(j + 1));
arrlValue.set(j + 1, tempNum2);
} else {
continue;
}
}
}
for (int i = 0; i < length2; i++) {
System.out.println(arrlIndex.get(i) + " " + arrlValue.get(i));
}
}
}
}