題目描述
數據表記錄包含表索引和數值,請對錶索引相同的記錄進行合併,即將相同索引的數值進行求和運算,輸出按照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;
/**
*
* All Rights Reserved !!!
*/
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while (scanner.hasNext()) {
int pares = Integer.parseInt(scanner.nextLine());
SortedMap<Integer, Integer> map = new TreeMap<>();
for (int i = 0; i < pares; i++) {
String[] nums = scanner.nextLine().split("\\s+");
addPare(map, nums);
}
System.out.print(mapToString(map));
}
scanner.close();
}
private static void addPare(SortedMap<Integer, Integer> map, String[] nums) {
int key = Integer.parseInt(nums[0]);
int val = Integer.parseInt(nums[1]);
if (map.containsKey(key)) {
map.put(key, map.get(key) + val);
} else {
map.put(key, val);
}
}
private static String mapToString(SortedMap<?, ?> map) {
StringBuilder builder = new StringBuilder();
for (SortedMap.Entry<?, ?> e : map.entrySet()) {
builder.append(e.getKey()).append(" ").append(e.getValue()).append("\n");
}
return builder.toString();
}
}