题解 | #合并表记录#

合并表记录

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());
        });


    }
}


全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

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