题解 | #合并表记录#

合并表记录

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的话顺序就会乱。

全部评论

相关推荐

MinGW_:直接投那个前端移动端就行,美团前端的岗位一直是叫这个名字的,哪怕是做内部系统只有网页没有移动端的组,招人的岗位也是这个名字
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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