题解 | #合并表记录#

合并表记录

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

TreeMap与HashMap不同点记录

排序

当有多条数据<Integer,Integer>存放到map中,而key值的大小是无序的,那么TreeMap会有一个自动排序的操作

例题

https://www.nowcoder.com/practice/de044e89123f4a7482bd2b214a685201?tpId=37&&tqId=21231&rp=1&ru=/ta/huawei&qru=/ta/huawei/question-ranking

答案


public class Main{
    public static void main(String args[]){
        Scanner sc = new Scanner(System.in);
        int size = sc.nextInt();
        TreeMap<Integer,Integer> map = new TreeMap();
        while(size>0){
            int key = sc.nextInt();
            int value = sc.nextInt();
            if(map.containsKey(key)){
                map.put(key,map.get(key)+value);
            }else{
                map.put(key,value);
            }
            size--;
        }
        Iterator iter = map.entrySet().iterator();
        while (iter.hasNext()){
            Map.Entry node = (Map.Entry) iter.next();
            System.out.println(node.getKey()+" "+node.getValue());
        }
    }
}

这个时候用HashMap就不行,题目中要求按顺序输出,如果这里用HashMap的话顺序就会乱。

全部评论

相关推荐

01-30 22:03
门头沟学院 Java
用微笑面对困难:我滴妈,【俩月】【实习】【主管】仨debuff吃满了,独立设计开发的项目写了绝大占比的运营板块,你独立开发,那维护、问题复盘、日志更新、bug、策划书全是自己整的? 不建议写那么大,可以从小出发更容易
点赞 评论 收藏
分享
卡卡罗特ovo:说起云智我就来气,约好了一面,结果面试官没来,ssob上问hr也未读,我还是专门请了半天假在家面试,恶心死了
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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