0
点赞
收藏
分享

微信扫一扫

HJ8 合并表记录

飞进科技 2022-04-15 阅读 47
java

描述

数据表记录包含表索引index和数值value(int范围的正整数),请对表索引相同的记录进行合并,即将相同索引的数值进行求和运算,输出按照index值升序进行输出。

提示:

0 <= index <= 11111111

1 <= value <= 100000

输入描述:

先输入键值对的个数n(1 <= n <= 500)
接下来n行每行输入成对的index和value值,以空格隔开

输出描述:

输出合并后的键值对(多行)

示例1

输入:

4
0 1
0 2
1 2
3 4

输出:

0 3
1 2
3 4

示例2

输入:

3
0 1
0 2
8 9

输出:

0 3
8 9
import java.util.*;

public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        while (in.hasNext()) {
            int a = in.nextInt();
            TreeMap<Integer, Integer> map = new
            TreeMap<Integer, Integer>(); // TreeMap 默认升序 且key唯一 如果插入key一样的值会覆盖之前的
            while (a > 0) {
                int b = in.nextInt();
                int c = in.nextInt();
                if (map.containsKey(b)) {
                    int d = map.get(b);
                    map.put(b, d + c);
                } else {
                    map.put(b, c);
                }
                a--;
            }

            //如何遍历输出一个TreeMap
            Set<Integer> keySet = map.keySet();
            Iterator<Integer> iter = keySet.iterator();
            while (iter.hasNext()) {
                int key = iter.next();
                System.out.println(key + " " + map.get(key));
            }

        }
    }
}

参考资料:

Java Map 键值对排序 按key排序和按Value排序_久曲健的技术博客_51CTO博客

Java Iterator(迭代器) | 菜鸟教程

举报

相关推荐

0 条评论