题解 | #合并表记录#

合并表记录

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

import java.util.HashMap;
import java.util.Scanner;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        //输入
        Scanner in = new Scanner(System.in);
        //获取长度
        Integer n = Integer.valueOf(in.nextLine());
        //用来维护合并值
        HashMap<Integer, Integer> map = new HashMap<>(n);
        for (int i = 0; i < n; i++) {
            //获取当前行的key
            int key = in.nextInt();
            //获取当前行的value
            int value = in.nextInt();
            //如果map已经存在key,就将value相加
            if (map.containsKey(key)) {
                map.put(key, map.get(key) + value);
                //否则新增key和value
            } else {
                map.put(key, value);
            }
        }
        for (Integer key : map.keySet()) {
            System.out.println(key + " " + map.get(key));
        }
    }
}

全部评论

相关推荐

点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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