题解 | #合并表记录#

合并表记录

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

import java.util.Scanner;
import java.util.*;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int num = Integer.parseInt(in.nextLine());
        HashMap<Integer, Integer> hashMap = new HashMap<>();
        HashSet<Integer> hashSet = new HashSet<>();
        for (int i = 0; i < num; i++) {
            String[] split = in.nextLine().split(" ");
            hashSet.add(Integer.parseInt(split[0]));
            if (hashMap.containsKey(Integer.parseInt(split[0]))) {
                int hash_index = Integer.parseInt(split[0]);
                hashMap.replace(hash_index,
                                hashMap.get(hash_index) + Integer.parseInt(split[1]));
            } else
                hashMap.put(Integer.parseInt(split[0]), Integer.parseInt(split[1]));
        }
        ArrayList<Integer> list = new ArrayList<>(hashSet);
        Collections.sort(list);
        for (Integer integer : list) {
            Integer sumValue = hashMap.get(integer);
            System.out.println(integer + " " + sumValue);
        }
    }
}

全部评论

相关推荐

2024-12-27 13:08
华南理工大学 Java
蝴蝶飞出了潜水钟丿:多看一眼就会💥
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务