華爲機試8 合併map元素

 

題目描述

數據表記錄包含表索引和數值(int範圍的整數),請對錶索引相同的記錄進行合併,即將相同索引的數值進行求和運算,輸出按照key值升序進行輸出。

輸入描述:


 

先輸入鍵值對的個數
然後輸入成對的index和value值,以空格隔開

輸出描述:

輸出合併後的鍵值對(多行)

示例1

輸入

4
0 1
0 2
1 2
3 4

輸出

0 3
1 2
3 4
public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        TreeMap<Integer, Integer> map = new TreeMap<>();
        while (sc.hasNext()) {
            int num = sc.nextInt();
            for (int i = 0; i < num; ++i) {
                int key = sc.nextInt();
                int value = sc.nextInt();
                if (map.containsKey(key))
                    map.put(key, map.get(key) + value);
                else
                    map.put(key,value);
            }
            Iterator it = map.entrySet().iterator();
            while(it.hasNext()){
                Map.Entry entry = (Map.Entry)it.next();
                System.out.println(entry.getKey()+" "+entry.getValue());
            }
            //for (Map.Entry<Integer, Integer> temp : map.entrySet()) {
            //    System.out.println(temp.getKey()+" "+temp.getValue());
            //}
        }
    }

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章