题解 | #JAVA合并表记录#

合并表记录

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


import java.util.*;

public class Main {
    public static void main(String[] args) {
        //创建Scanner对象从控制台获取输入
        Scanner scanner = new Scanner(System.in);
        //读取哈希表的长度
        int tableSize=scanner.nextInt();
        //创建map对象,类型为<Integer, Integer>,指定容量为tableSize
        Map<Integer, Integer> table = new HashMap<>(tableSize);
        
        //使用for循环遍历tableSize次
        for ( int i = 0 ; i < tableSize ; i++) {
            //读取键值对
            int key = scanner.nextInt();
            int value = scanner.nextInt();

            //如果map包含此键,获取原值并加上新值
            if ( table.containsKey(key)){
                table.put(key,table.get(key)+value);
            }

             //否则直接添加新键值对
            else{
                table.put(key,value);
            }
        }

        //遍历map中的所有键
        for ( Integer key : table.keySet()){
            //输出键值对
            System.out.println(key+" "+table.get(key));
        }
    }
}
/**
这个采用hash表存放数据就好了,每次输入查询是否有存在的key

存在就将value累加到表中,最后输出表。
 */

#java#
全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务