zoukankan      html  css  js  c++  java
  • 16:Merge

    题目描述

    数据表记录包含表索引和数值,请对表索引相同的记录进行合并,即将相同索引的数值进行求和运算,输出按照key值升序进行输出。

    输入描述:先输入键值对的个数,然后输入成对的index和value值,以空格隔开

    输出描述:输出合并后的键值对(多行)

    输入例子:

    4

    0 1

    0 2

    1 2

    3 4

    输出例子:

    0 3

    1 2

    3 4

    package prctice01;
    import java.awt.List;
    /*16 题目描述
    数据表记录包含表索引和数值,请对表索引相同的记录进行合并,即将相同索引的数值进行求和运算,输出按照key值升序进行输出。
    输入描述:先输入键值对的个数,然后输入成对的index和value值,以空格隔开
    输出描述:输出合并后的键值对(多行)
    输入例子:
    4
    0 1
    0 2
    1 2
    3 4
    输出例子:
    0 3
    1 2
    3 4*/
    import java.util.Scanner;
    import java.util.SortedMap;
    import java.util.TreeMap;
     
    public class MergeKeyValue {
        public static void main(String[] args) {
            Scanner in = new Scanner(System.in);
            int num = Integer.parseInt(in.nextLine());
            SortedMap<Integer, Integer> map = new TreeMap<>();
            for(int i = 0;i<num;i++)
            {
                String[] input = in.nextLine().split("\s+");
                sortMap(input,map);
            }
            for (SortedMap.Entry<Integer, Integer> treeMap : map.entrySet()) {
                System.out.println(treeMap.getKey() + " "+ treeMap.getValue() );
            }
            
        }
        private static void sortMap(String[] input, SortedMap<Integer, Integer> map) {
            int key = Integer.parseInt(input[0]);
            int value = Integer.parseInt(input[1]);
            if(map.containsKey(key))
            {
                map.put(key, map.get(key)+value);
            }
            else 
                map.put(key, value);
        }
    }
  • 相关阅读:
    前端大文件上传方法(深度好文)
    windows版idea 2018.3.5版 永久激活教程
    性能优化随笔
    使用java画一张海报
    Gson杂记录
    Gson转Map时,Int会变成double解决方法
    浅析VO、DTO、DO、PO的概念、区别和用处
    SpringCloud框架搭建+实际例子+讲解+系列五
    raid总结
    MD5与SHA1
  • 原文地址:https://www.cnblogs.com/newcoder/p/5765480.html
Copyright © 2011-2022 走看看