题解 | #合并表记录#

合并表记录

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

主要复习知识点

import java.util.*;
public class Main{
    public static void main(String[] args){
        Scanner in=new  Scanner(System.in);
        TreeMap<Integer,Integer> map=new TreeMap<>();
        String a=in.next();
        int num=Integer.valueOf(a)*2;
        int pre=0;
        for(int i=0;i<num;i++){
            if(i%2==0){
                String b=in.next();
                pre=Integer.valueOf(b);
            }else{
                String c=in.next();
                int d=Integer.valueOf(c);
                map.put(pre,map.getOrDefault(pre,0)+d); 
            }            
        }
        
        //第一种排序
//         int s=map.size();
//         int[] ary=new int[s];
//         int o=0;
//         for(int e: map.keySet()){
//             ary[o]=e;o++;    
//         }
//         Arrays.sort(ary);
//         for(int m=0;m<s;m++){
//             System.out.println(ary[m]+" "+map.get(ary[m]));  
//         }
       
        //第二种排序
        //这里的map可以说HashMap
//         SortedMap<Integer,Integer> sortmap=new TreeMap<>(map);
//         for(int e:sortmap.keySet()){
//             System.out.println(e+" "+map.get(e));    
//         }
//         SortedMap<Integer,Integer> sortmap=new TreeMap<>(map);
        
        //第三种用Treemap排序
        for(int e: map.keySet()){
            System.out.println(e+" "+map.get(e));    
        }
    } 
}
全部评论

相关推荐

投递美团等公司9个岗位
点赞 评论 收藏
转发
2 3 评论
分享
牛客网
牛客企业服务