题解 | #合并表记录#

合并表记录

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

import java.util.Scanner;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;
import java.util.Arrays;
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        // 注意 hasNext 和 hasNextLine 的区别
        int n = in.nextInt();
        int times = 0;
        HashMap<Integer,Integer> map = new HashMap<Integer,Integer>();
        while(times<n){
            int index = in.nextInt();
            int value = in.nextInt();
            int temp = 0;
            if(!map.containsKey(index))
                map.put(index,value);
            else
                temp = map.get(index);
                value = value+temp;
                map.put(index,value);

            times++;
        }

        Set set = map.keySet();
        Object[] array=set.toArray();
        Arrays.sort(array);
        for(Object key:array){
            int res = map.get(key);
            System.out.println(key+" "+res);
        }
        // Iterator<Integer> iterator = map.keySet().iterator();
        // while(iterator.hasNext()){
        //     int key = iterator.next();
        //     int res = map.get(key);
        //     System.out.println(key+" "+res);
        // }
    }
}

全部评论

相关推荐

我不行了,我真过不了第二关
码农索隆:嘿,哥们连界面都进去去,更别提玩了
点赞 评论 收藏
分享
用微笑面对困难:只要你保证项目和获奖都是真的就行尤其是“对战,总负责人”啊这些套职,基本上队员,打杂的都这么写
点赞 评论 收藏
分享
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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