题解 | #合并表记录#
合并表记录
http://www.nowcoder.com/practice/de044e89123f4a7482bd2b214a685201
import java.util.*;
public class Main{
public static void main(String[] args){
Scanner scanner1 = new Scanner(System.in);
int n = Integer.valueOf(scanner1.nextLine());
int len = 0;
if(n < 1 || n > 500) return;
Map<Integer,Integer> map = new HashMap<>();
while(len < n && scanner1.hasNext()) {
String[] strArray = scanner1.nextLine().split(" ");
if(strArray.length > 2) {
continue;
}
Integer one = Integer.valueOf(strArray[0]);
Integer two = Integer.valueOf(strArray[1]);
if(map.containsKey(one)){
map.put(one,map.get(one) + two);
}else{
map.put(one,two);
}
len++;
}
if(len==n) {
LinkedHashMap<Integer,Integer> res = ConTableRec(map);
for(Map.Entry<Integer,Integer> m:res.entrySet()){
System.out.println(m.getKey() +" " + m.getValue());
}
}
}
private static LinkedHashMap<Integer,Integer> ConTableRec(Map<Integer,Integer> maps){
LinkedHashMap<Integer,Integer> map = new LinkedHashMap<>();
//定义一个key数组
int[] keyArray = new int[maps.keySet().size()];
Iterator<Map.Entry<Integer,Integer>> it = maps.entrySet().iterator();
int i = 0;
while(it.hasNext() && i<keyArray.length){
Map.Entry<Integer,Integer> entry = it.next();
keyArray[i] = entry.getKey();
i++;
}
//对数组进行升序排序
for(int s = 0;s < keyArray.length;s++){
for(int j = keyArray.length - 1;j > s;j--){
if(keyArray[s]>keyArray[j]){
int tmp = keyArray[j];
keyArray[j] = keyArray[s];
keyArray[s] = tmp;
}
}
}
//对map遍历赋值
for(int t = 0;t < keyArray.length;t++){
map.put(keyArray[t],maps.get(keyArray[t]));
}
return map;
}
}