题解 | #合并表记录#

合并表记录

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

合并 ,Set,不重复可以合并,Map的Key是Set,
index排序,SortedMap可以实现对键的排序

import java.util.*;

 
public class Main{
     public static void main(String[] args) throws Exception{
        Scanner sc = new Scanner(System.in);
        int n = Integer.valueOf(sc.nextLine());

        HashMap<Integer,Integer> map = new HashMap();
        for(int i = 0 ;i <n ; i++){
            String[] nums = sc.nextLine().split(" ");

            int index = Integer.valueOf(nums[0]);
            int value = Integer.valueOf(nums[1]);
            if(map.get(index) != null){
                int t = map.get(index);
                value += t;

            }//合并相同

            map.put(index,value);
        }//for
        //键值排序
        SortedMap<Integer,Integer> sortedMap = new TreeMap<>(map);
        sortedMap.entrySet().forEach(entry ->{
            System.out.println(entry.getKey()+" "+entry.getValue());
        });


    }
}


全部评论

相关推荐

之前自己不懂事,投了字节,基本是自己第一次面试,一面就挂了
观水:前几天有个学化学的做前端,加上实习面了22次字节最后成功了
点赞 评论 收藏
分享
脑袋锈住了:你这算啥,哥们中科院中强所硕士,本科211,叫我去干分拣,时薪20
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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