题解 | #合并表记录#
合并表记录
http://www.nowcoder.com/practice/de044e89123f4a7482bd2b214a685201
方法1:数组,简单,但浪费空间
import java.util.Scanner;
public class Main{
public static int[] arr = new int[11111112];
public static void main(String[] args){
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int flag = -1;
for(int i = 1; i <= n; i++){
int a = in.nextInt();
int b = in.nextInt();
arr[a] += b;
}
for(int i = 0; i < 11111112; i++){
if(arr[i] != 0){
System.out.println(i + " " + arr[i]);
}
}
}
}
方法2: hashmap
import java.util.*;
public class Main{
public static void main(String[] args){
Scanner in = new Scanner(System.in);
int n = in.nextInt();
HashMap<Integer,Integer> map = new HashMap<Integer,Integer>();
for(int i=0; i < n; i++){
int a = in.nextInt();
int b = in.nextInt();
if(map.isEmpty() || !map.containsKey(a)){
map.put(a,b);
}
else if(map.containsKey(a)){
int temp = map.get(a);
map.put(a,temp + b);
}
}
//排序
Set set = map.keySet();
Object[] a1 = set.toArray();
Arrays.sort(a1);
for(Object key : a1){
System.out.println(key + " " + map.get(key));
}
}
}