题解 | 合并表记录

合并表记录

https://www.nowcoder.com/practice/de044e89123f4a7482bd2b214a685201

import java.util.*;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        //有序输出,所以使用TreeMap
        TreeMap<Integer, Integer> table = new TreeMap<>(); //创建哈希表
        while (sc.hasNext()) {
            int n = sc.nextInt();
            for (int i = 0; i < n; i++) {
                int key = sc.nextInt();
                int value = sc.nextInt();
                //若key已存在,就取出旧值,加上新值后存入
                if (table.containsKey(key)) {
                    table.put(key, table.get(key) + value);
                }
                //不存在则直接存入
                else {
                    table.put(key, value);
                }
            }
        }
        //table.keySet() 获取所有的键,增强for循环打印哈希表
        for (Integer key : table.keySet()) {
            System.out.println(key + " " + table.get(key));
        }
    }
}

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务