题解 | #合并表记录#

合并表记录

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

import java.util.*;
import java.util.stream.*;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        Map<Integer,Integer> res = new HashMap<>();
        while (in.hasNextInt()) {
            int count = in.nextInt();
            for(int i=0;i<count;i++){
                int key = in.nextInt();
                int value = in.nextInt();
                res.put(key,res.getOrDefault(key,0)+value);
            }   
        }
        List<Integer> keyList = res.keySet().stream().sorted().collect(Collectors.toList());
        keyList.forEach(key ->{
            System.out.println(key+" "+res.get(key));
        });
    }
}

注意试题对应的输入形式和理解的有点出入,根据描述,那么就是每次输入都是一个正整数类型,而并非第一次输入一个数字,然后后续每次都是一行输入一个key[space]value。

全部评论

相关推荐

06-15 18:44
黄淮学院 Java
Lynn012:如果是居民楼还是算了吧,看着有点野呢
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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