题解 | #合并表记录#

合并表记录

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

//放入map, 对map的key进行判断,key有重复的就重新put进map更新对应的value的值、
//重点是数据结构的选择,
//这里没用hashmap, 而是用的TreeMap ,因为hashmap是无序的,TreeMap是有序的,
//当key的数量非常多的时候,TreeMap可以保证有序。
import java.util.*;
public class Main{
    public static void  main(String[] args){
        Scanner sc = new Scanner(System.in);
        TreeMap<Integer,Integer> outMap = new TreeMap<Integer,Integer>();
        //对输入数据用空格切割
        while(sc.hasNext()){
           String inStr = sc.nextLine();
           String[] arr  = inStr.split(" ");
            if(arr.length>1){
               int key = Integer.parseInt(arr[0]);
               int value = Integer.parseInt(arr[1]);
                if(!outMap.containsKey(key)){
                    outMap.put(key,value);
                }else{
                    outMap.put(key,outMap.get(key) + value);
                }
            }
        }
               //遍历map输出
//                for(String key :outMap.keySet()){
//                    System.out.println(key +" " +outMap.get(key));
//                }
            for (Map.Entry<Integer, Integer> entry : outMap.entrySet()) {
                    System.out.println(entry.getKey()+" "+entry.getValue());
            }
    }
}
全部评论

相关推荐

这是什么操作什么意思,这公司我服了...
斯派克spark:意思是有比你更便宜的牛马了
点赞 评论 收藏
分享
06-13 10:15
门头沟学院 Java
想去夏威夷的大西瓜在...:我也是27届,但是我现在研一下了啥项目都没有呀咋办,哎,简历不知道咋写
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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