题解 | #合并表记录#
合并表记录
https://www.nowcoder.com/practice/de044e89123f4a7482bd2b214a685201
import java.util.HashMap;
import java.util.Scanner;
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
public static void main(String[] args) {
//输入
Scanner in = new Scanner(System.in);
//获取长度
Integer n = Integer.valueOf(in.nextLine());
//用来维护合并值
HashMap<Integer, Integer> map = new HashMap<>(n);
for (int i = 0; i < n; i++) {
//获取当前行的key
int key = in.nextInt();
//获取当前行的value
int value = in.nextInt();
//如果map已经存在key,就将value相加
if (map.containsKey(key)) {
map.put(key, map.get(key) + value);
//否则新增key和value
} else {
map.put(key, value);
}
}
for (Integer key : map.keySet()) {
System.out.println(key + " " + map.get(key));
}
}
}
查看5道真题和解析