题解 | #合并表记录#
合并表记录
http://www.nowcoder.com/practice/de044e89123f4a7482bd2b214a685201
用 TreeMap 来处理合并和排序。
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int size = sc.nextInt();
// merge value by key, tree map can handle sorting
Map<Integer, Integer> numMap = new TreeMap<>();
for (int i = 0; i < size; i++) {
int key = sc.nextInt();
int value = numMap.getOrDefault(key, 0);
value += sc.nextInt();
numMap.put(key, value);
}
for (Map.Entry<Integer, Integer> entry : numMap.entrySet()) {
System.out.println(entry.getKey() + " " + entry.getValue());
}
}
}
上海得物信息集团有限公司公司福利 1243人发布
查看12道真题和解析