算法-合并表记录
题目描述
数据表记录包含表索引和数值(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 input = new Scanner(System.in);
String inLine = input.nextLine();
int line = Integer.parseInt(inLine);
Map<Integer, Integer> mp = new HashMap<>();
for(int i = 0; i < line; i++) {
String comb = input.nextLine();
String[] kv = comb.split(" ");
int key = Integer.parseInt(kv[0]);
int val = Integer.parseInt(kv[1]);
if(mp.containsKey(key)) {
int value = mp.get(key) + val;
mp.put(key,value);
} else {
mp.put(key,val);
}
}
List<Integer> Allkeys = new ArrayList<>();
for(Integer kk: mp.keySet()){
Allkeys.add(kk);
}
Collections.sort(Allkeys);
for(int a = 0; a < Allkeys.size(); a++){
System.out.println(Allkeys.get(a) + " " + mp.get(Allkeys.get(a)));
}
}
}
笔记:
- 判断一个map中是否存在某个key值:
Map<String, Integer> map = new HashMap<>();
String key = test;
map.containsKey(test); //返回一个Boolean值,用来判断map中是否存在key值
- 对List进行排序,使用方法
Collections.sort(arrayList);
,
字母数字都可以排序。