題目描述:
數據表記錄包含表索引和數值,請對錶索引相同的記錄進行合併,即將相同索引的數值進行求和運算,輸出按照key值升序進行輸出。
輸入描述:
先輸入鍵值對的個數
然後輸入成對的index和value值,以空格隔開
輸出描述:
輸出合併後的鍵值對(多行)
示例1:
輸入:
4
0 1
0 2
1 2
3 4
輸出:
0 3
1 2
3 4
代碼:
import java.util.Map;
import java.util.Scanner;
import java.util.Set;
import java.util.TreeMap;
public class Main {
public static void main (String[] args) {
Scanner in = new Scanner(System.in);
Map<Integer,Integer> map = new TreeMap<Integer,Integer>();
int n = in.nextInt();
in.nextLine();
map.put(in.nextInt(), in.nextInt());
in.nextLine();
for(int i=1;i<n;i++) {
int a = in.nextInt();
int b = in.nextInt();
if(map.containsKey(a)) {
int c = map.get(a);
// map.remove(a);
map.put(a, b+c);
}
else {
map.put(a, b);
}
}
Set<Integer> s = map.keySet();
for(Integer i : s) {
System.out.println(i+" "+map.get(i));
}
}
}