题解 | 合并表记录

合并表记录

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

import java.util.*;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        //最重要的是:
        //1. TreeMap<key, value>会自动按 key 升序排序
        //2. TreeMap<>的函数put(key,map.getOrDefault(key,0)+value):
        //   map.put(x, 原来的值 + 新的值y)。把x位置原来的数,加上y,再存回去
        //3. getOrDefault(key,0)
        //   去map里拿键key对应的value。如果有x就拿出它的值,如果没有x就返回0
        
        Scanner in = new Scanner(System.in);
        int n = in.nextInt();
        TreeMap<Integer, Integer> map = new TreeMap<>();

        for (int i = 0; i < n; i++) {
            int x = in.nextInt();  //索引
            int y = in.nextInt();  //数值

            // 相同索引累加数值
            map.put(x, map.getOrDefault(x, 0) + y);
        }

        //增强for遍历输出 map
        for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
            System.out.println(entry.getKey() + " " + entry.getValue());
        }

    }
}

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

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