日期:2014-05-20 浏览次数:20755 次
int[][] a={{2,3},{11,2},{7,4},{9,3}}; int[][] b={{3,4},{9,1},{2,2},{6,3},{11,1}};
int[][] c={{2,5},{3,4},{6,3},{7,4},{9,4},{11,3}};
int[][] a={{2,3},{11,2},{7,4},{9,3}}; int[][] b={{3,4},{9,1},{2,2},{6,3},{11,1}}; Map<Integer, Integer> map = new HashMap<Integer, Integer>(); for (int[] x : a) { map.put(x[0], x[1]); } for (int[] x : b) { Integer y = map.get(x[0]); if (y != null) { map.put(x[0], y+x[1]); } else { map.put(x[0], x[1]); } } int[][] result = new int[map.size()][2]; Set<Integer> keys = map.keySet(); // Integer可能不需要,不过稳妥一点,还是直接,保证顺序 // Set<Integer> keys = new TreeSet<Integer>(map.keySet()); int count = 0; for (Integer key:keys) { result[count][0] = key; result[count++][1] = map.get(key); }
------解决方案--------------------
如果,a[i][0]和b[i][0]的范围已知,而且a[i][1]和b[i][1]都是正数的话,可以更简化
int[][] a={{2,3},{11,2},{7,4},{9,3}}; int[][] b={{3,4},{9,1},{2,2},{6,3},{11,1}}; int[] c = new int[20/*key的范围,可能考虑负数什么*/]; for (int[] x:a) { c[x[0]] += x[1]; } for (int[] x:b) { c[x[0]] += x[1]; } int count = 0; int[][] temp = new int[c.length][2]; for (int i = 0; i < c.length; i++) { if (c[i] > 0) { temp[count][0] = i; temp[count++][1] = c[i]; } } int[][] result = new int[count][2]; System.arraycopy(temp, 0, result, 0, count);
------解决方案--------------------