java----------华为机试------------合并表记录
题目描述
数据表记录包含表索引和数值,请对表索引相同的记录进行合并,即将相同索引的数值进行求和运算,输出按照key值升序进行输出。
输入描述:
先输入键值对的个数 然后输入成对的index和value值,以空格隔开
输出描述:
输出合并后的键值对(多行)
输入例子:
4
0 1
0 2
1 2
3 4
解法一:暴力
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); while (sc.hasNext()) { int num = sc.nextInt(); int[] a = new int[10000]; // 定义一个大数组 for (int j = 0; j < num; j++) { // num个循环,每个循环输入一组 int i = sc.nextInt(); int b = sc.nextInt(); a[i] += b; // 以i为key,b为value,不断累加 } } for (int i = 0; i < num; i++) { if (a[i] != 0) { System.out.println(i + " " + a[i]);// 输出所有非零值; } } } } }
解法二:使用TreeMap
import java.util.Map; import java.util.Scanner; import java.util.TreeMap; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); while (sc.hasNext()) { Map<Integer, Integer> map = new TreeMap<Integer, Integer>();// 定义map int n = sc.nextInt(); // 输入n值 for (int i = 0; i < n; i++) { int s = sc.nextInt(); int value = sc.nextInt(); // 输入Key和Value值 if (map.containsKey(s)) { // 如果key=s处有值,则用sum替换原值 map.put(s, map.get(s) + value); } else { // 如果无值,直接放入 map.put(s, value); } } // 迭代输出 for (Integer key : map.keySet()) { System.out.println(key + " " + map.get(key)); } } } }