题解 | #合并表记录#
合并表记录
http://www.nowcoder.com/practice/de044e89123f4a7482bd2b214a685201
package com.company.niuke;
import java.util.Map;
import java.util.Scanner;
import java.util.TreeMap;
/**
* @ProjectName: leetcode
* @Package: com.company.niuke
* @ClassName: MergeMap
* @Author: Administrator
* @Description: 合并
* @Date: 2022/2/16 21:58
* @Version: 1.0
*/
public class MergeMap {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = Integer.valueOf(scanner.nextLine());
Map<Integer, Integer> map = new TreeMap<>(); //输出需要排序,所以使用TreeMap
for (int i = 0; i < n; i++) {
String entity = scanner.nextLine();
String[] split = entity.split(" ");
if (map.containsKey(Integer.valueOf(split[0]))) {
map.put(Integer.valueOf(split[0]), map.get(Integer.valueOf(split[0])) + Integer.valueOf(split[1]));
} else {
map.put(Integer.valueOf(split[0]),Integer.valueOf(split[1]));
}
}
for (Integer index: map.keySet()) {
System.out.println(index + " " + map.get(index));
}
}
}