0
点赞
收藏
分享

微信扫一扫

【华为OJ8】合并表记录


题目描述

数据表记录包含表索引和数值,请对表索引相同的记录进行合并,即将相同索引的数值进行求和运算,输出按照key值升序进行输出。



输入描述:



先输入键值对的个数 然后输入成对的index和value值,以空格隔开




输出描述:



输出合并后的键值对(多行)



输入例子:


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.TreeMap;

public class Main{
public static void addMap(Map<Integer, Integer> map,String[] nums){

int key=Integer.parseInt(nums[0]);
int value=Integer.parseInt(nums[1]);

//如果将要添加的值已经存在,就添加其value值
if(map.containsKey(key)){
map.put(key, map.get(key)+value);
}else{
//没有就直接加入
map.put(key, value);
}

}

public static String mapToString(Map<Integer,Integer> map){
StringBuilder sb=new StringBuilder();

for(Map.Entry<Integer, Integer> entrySet:map.entrySet()){
sb.append(entrySet.getKey()).append(" ").append(entrySet.getValue()).append("\n");
}
return sb.toString();

}
public static void main(String[] args) {
Map<Integer,Integer> map=new TreeMap<>();
Scanner sc=new Scanner(System.in);

while(sc.hasNext()){
//public String nextLine()
int num=Integer.parseInt(sc.nextLine());
for(int i=0;i<num;i++){
/*\\d表示 0-9 的数字,
\\s表示 空格,回车,换行等空白符,
\\w表示单词字符(数字字母下划线) */
//正则表达式:\s表示空格,应该是以空格开头或结尾都会被截取到。
String[] nums=sc.nextLine().split("\\s+");
addMap(map, nums);
}
System.out.print(mapToString(map));
}
sc.close();
}
}


举报

相关推荐

0 条评论