華為機試 牛客網 HJ8 合并表記錄
- 描述
- 輸入描述:
- 輸出描述:
- 示例1
- 題解
- 反思
描述
資料表記錄包含表索引和數值(int範圍的正整數),請對表索引相同的記錄進行合并,即将相同索引的數值進行求和運算,輸出按照key值升序進行輸出。
輸入描述:
先輸入鍵值對的個數
然後輸入成對的index和value值,以空格隔開
輸出描述:
輸出合并後的鍵值對(多行)
示例1
輸入:
4
0 1
0 2
1 2
3 4
輸出:
0 3
1 2
3 4
題解
import java.util.*;
public class Main{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int num = sc.nextInt();
TreeMap<Integer,Integer> treemap = new TreeMap<>();
for(int i=0;i<num;i++){
int key = sc.nextInt();
int value = sc.nextInt();
if(treemap.containsKey(key))
treemap.put(key,treemap.get(key)+value);
else
treemap.put(key,value);
}
for(Map.Entry<Integer,Integer> entry:treemap.entrySet())
System.out.println(entry.getKey()+" "+entry.getValue());
}
}
反思
要會treemap的使用與特點,以及他的周遊