题解 | #合并表记录#
合并表记录
https://www.nowcoder.com/practice/de044e89123f4a7482bd2b214a685201
import java.util.Arrays; 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); HashMap<Integer,Integer> map = new HashMap<Integer,Integer>(); int count = in.nextInt(); while(count > 0){ count--; int indexIn = in.nextInt(); int valueIn = in.nextInt(); if(map.containsKey(indexIn)){ // 如果已经存在此index int valueOld = map.get(indexIn); // 获取已经存在的value map.computeIfPresent(indexIn, (key,value)->(valueIn+valueOld)); // 重新计算新的value并填入map } else{ // 没有存在此index 则把键值对加入map map.put(indexIn,valueIn); } } int [] indexTemp = new int [map.size()]; // 承装所有index int j = 0; for(Integer i: map.keySet()){ // 取出所有key 装入indexTemp indexTemp[j] = i; j++; } Arrays.sort(indexTemp); // 给所有key排序 for(Integer i:indexTemp){ // 用有序的key输出 对应的value System.out.println(i + " " + map.get(i)); } } }