题解 | #合并表记录#
合并表记录
http://www.nowcoder.com/practice/de044e89123f4a7482bd2b214a685201
解题思路:
首先读取本次需要的数组长度,数组为二维的,一维存下标,一维存值。然后对二维数组进行排序,对一般的数组排序采用:
Arrays.sort(T[] arr,new Comparator<T>(){ public int compare(T t1, T t2) { // 具体比较方式,判断t1和t2的大小关系 } });
import java.util.Arrays; import java.util.Comparator; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scan = new Scanner(System.in); int size = scan.nextInt(); int[][] data = new int[size][2]; for (int i = 0; i < size; i++) { data[i][0] = scan.nextInt(); data[i][1] = scan.nextInt(); } Arrays.sort(data, new Comparator<int[]>() { @Override public int compare(int[] o1, int[] o2) { return o1[0] - o2[0]; } }); int key = data[0][0]; int val = data[0][1]; for (int i = 1; i < size; i++) { if (data[i][0] == key) { val += data[i][1]; } else { System.out.println(key + " " + val); key = data[i][0]; val = data[i][1]; } } System.out.println(key + " " + val); } }