题解 | #合并表记录#

合并表记录

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

import java.util.Scanner;
import java.util.*;
import java.util.stream.Collectors;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        // 注意 hasNext 和 hasNextLine 的区别
        int rown = 0;
        HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
        int flag = 0;

        while (in.hasNextLine()) { // 注意 while 处理多个 case
            String n = in.nextLine();

            if (flag == 0) {
                rown = Integer.parseInt(n);
                flag++;
                continue;
            }
            if (flag > (rown + 1)) {
                break;
            }
            String array[] = n.split(" ");


            if (map.containsKey(Integer.parseInt(array[0]))) {
                Integer old = map.get(Integer.parseInt(array[0]));
                map.put(Integer.parseInt(array[0]), Integer.parseInt(array[1]) + old);
            } else {
                map.put(Integer.parseInt(array[0]), Integer.parseInt(array[1]));
            }

        }

        Set<Integer> integers = map.keySet();
        List<Integer> collect = integers.stream().sorted().collect(Collectors.toList());
        for (Integer integer : collect) {
            System.out.println(integer + " " + map.get(integer));
        }
    }
}

全部评论

相关推荐

完美的潜伏者许愿简历通过:我上表jd,请求封我做后端大将军的事,北京有消息了:竟然不许!!! 他们一定是看我没有实习,这才故意驳回我的请求!
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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