题解 HJ8| #合并表记录#
合并表记录
https://www.nowcoder.com/practice/de044e89123f4a7482bd2b214a685201
import java.util.Scanner; // 注意类名必须为 Main, 不要有任何 package xxx 信息 public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); int a = in.nextInt(); int[] index = new int[a]; int[] value = new int[a]; int sum = 0; for (int i = 0; i < a; i++) { int b = in.nextInt(); int c = in.nextInt(); int cout = 0; for (int j = 0; j < sum; j++) { if (b == index[j]) { value[j] += c; cout = 1; } } if (cout == 0) { index[sum] = b; value[sum] = c; sum++; } } //排序 for (int i = 0; i < sum - 1; i++) { for (int j = 0; j < sum - 1-i; j++) { if (index[j] > index[j + 1]) { int tmp = index[j]; int temp = value[j]; index[j] = index[j + 1]; value[j] = value[j + 1]; index[j + 1] = tmp; value[j + 1] = temp; } } } //输出 for (int i = 0; i < sum; i++) { System.out.print(index[i]); System.out.print(' '); System.out.println(value[i]); } } }
合并记录表,首先是要有俩个数组,在不用额外库,不用tree、map的情况下,就需要构造俩个数组了
先定义int类去接收总数,建立俩个总数大小的数组
int a = in.nextInt();
int[] index = new int[a];
int[] value = new int[a];
int sum = 0;
之后使用for循环
for (int i = 0; i < a; i++) {
int b = in.nextInt();//接收输入
int c = in.nextInt();//接受输入
int cout = 0;//判断是否有重复,我懒得用bool了
for (int j = 0; j < sum; j++) {//在index已有的sum范围内去寻找有没有和接收到的索引重复的,有就值相加
if (b == index[j]) {
value[j] += c;
cout = 1;
}
}
if (cout == 0) {//没有就放入数组中,数组总数sum++
index[sum] = b;
value[sum] = c;
sum++;
}
}
这样就获得了一个没有重复的俩个数组,接着是排序,依然是熟悉的冒泡排序
for (int i = 0; i < sum - 1; i++) {
for (int j = 0; j < sum - 1-i; j++) {
if (index[j] > index[j + 1]) {
int tmp = index[j];
int temp = value[j];
index[j] = index[j + 1];
value[j] = value[j + 1];
index[j + 1] = tmp;
value[j + 1] = temp;
}
}
}
最后是输出
for (int i = 0; i < sum; i++) {
System.out.print(index[i]);
System.out.print(' ');
System.out.println(value[i]);//print不带换行,当然也可以自己加入换行符,println自带换行
}
}
}
#华为od题库#随便发发而已