题解 | #合并表记录#
合并表记录
http://www.nowcoder.com/practice/de044e89123f4a7482bd2b214a685201
import java.util.Scanner; import java.util.Set; import java.util.TreeMap; public class Main {
public static void main(String[] args) {
TreeMap<Integer,Integer> map = new TreeMap<>();
Scanner sc = new Scanner(System.in);
// System.out.print("请输入键值对个数:"); int n = sc.nextInt(); // System.out.println("请输入键值对:"); sc.nextLine(); for (int i = 0; i < n; i++) { String kv = sc.nextLine(); String[] s = kv.split(" "); Integer key = Integer.parseInt(s[0]); Integer value = Integer.parseInt(s[1]); if(map.containsKey(key)){ value = map.get(key)+value; map.put(key,value); }else { map.put(key,value); } } Set integers = map.keySet(); for (Integer integer : integers) { System.out.println(integer+" "+map.get(integer)); } }
}