题解 | #华为no.8 合并表记录#

合并表记录

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

使用排序map(引入java.io.*),遍历输入并且遍历输出

import java.io.*;
public class Main{
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        TreeMap<Integer,Integer> map = new TreeMap<>();
        for(int i=0;i<n;i++) {
            int key = sc.nextInt();
            int val = sc.nextInt();
            if (map.containsKey(key)) {
                map.put(key,val+map.get(key));
            } else {
                map.put(key,val);
            }
        }
        Iterator it = map.keySet().iterator();
        while (it.hasNext()) {
            int key = (Integer) it.next();
            System.out.println(key+" "+map.get(key));
        }
    }
}
全部评论

相关推荐

10-22 19:44
门头沟学院 Java
面了100年面试不知...:那我得去剪个头
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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