题解 | #合并表记录#
合并表记录
https://www.nowcoder.com/practice/de044e89123f4a7482bd2b214a685201
import java.util.*; import java.util.stream.*; // 注意类名必须为 Main, 不要有任何 package xxx 信息 public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); Map<Integer,Integer> res = new HashMap<>(); while (in.hasNextInt()) { int count = in.nextInt(); for(int i=0;i<count;i++){ int key = in.nextInt(); int value = in.nextInt(); res.put(key,res.getOrDefault(key,0)+value); } } List<Integer> keyList = res.keySet().stream().sorted().collect(Collectors.toList()); keyList.forEach(key ->{ System.out.println(key+" "+res.get(key)); }); } }
注意试题对应的输入形式和理解的有点出入,根据描述,那么就是每次输入都是一个正整数类型,而并非第一次输入一个数字,然后后续每次都是一行输入一个key[space]value。