题解 | #合并表记录#
合并表记录
https://www.nowcoder.com/practice/de044e89123f4a7482bd2b214a685201
import java.util.Scanner; import java.util.TreeMap; public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); String s = in.nextLine(); int i = Integer.valueOf(s); TreeMap<Integer,Integer> map = new TreeMap<>(); for(int k = 0; k < i; k++){ String s1 = in.nextLine(); String[] ss = s1.split(" "); int key = Integer.valueOf(ss[0]); int value = Integer.valueOf(ss[1]); if(map.containsKey(key)){ int val = map.get(key); map.put(key,val + value); }else{ map.put(key,value); } } for (Integer index : map.keySet()){ System.out.println(index + " " + map.get(index)); } } } 使用TreeMap能够较好的完成本题,因为TreeMap中的元素会按大小排序 不要使用HashMap,因为HashMap是无序的。