题目
题解
用map哈希表存储key、value,存在相同key则把value值相加。
import java.util.*;
import java.util.stream.Collectors;
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = Integer.parseInt(in.nextLine());
List<String> list = new ArrayList<>(n);
for (int i = 0; i < n; i++) {
list.add(in.nextLine());
}
Map<Integer, Integer> integerMap = merge(list);
List<Integer> keyList = integerMap.keySet().stream().sorted().collect(
Collectors.toList());
for (Integer key : keyList) {
System.out.println(key + " " + integerMap.get(key));
}
}
public static Map<Integer, Integer> merge(List<String> list) {
Map<Integer, Integer> map = new HashMap<>();
for (String s : list) {
String[] split = s.split(" ");
int index = Integer.parseInt(split[0]);
int value = Integer.parseInt(split[1]);
map.put(index, map.getOrDefault(index, 0) + value);
}
return map;
}
}
时间复杂度:O(N)