日期:2014-05-20  浏览次数:20722 次

两个数组如何高速合并?
我有两个数组
Java code

         int[][] a={{2,3},{11,2},{7,4},{9,3}};
        int[][] b={{3,4},{9,1},{2,2},{6,3},{11,1}};



要求a和b数组合并 结果变为
Java code

int[][] c={{2,5},{3,4},{6,3},{7,4},{9,4},{11,3}};



不能用两个for嵌套 意思就是性能要比两个for嵌套要高

------解决方案--------------------
Java code
    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]都是正数的话,可以更简化
Java code
    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);

------解决方案--------------------
探讨

引用:

map我大致看了一下实现 get方法和contain方法之类的还是for嵌套的 而且不是都说数组是性能最好的么

建议你再看十遍

------解决方案--------------------
探讨

如果,a[i][0]和b[i][0]的范围已知,而且a[i][1]和b[i][1]都是正数的话,可以更简化
Java code
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的范围,可能考虑负数什么*/……

------解决方案--------------------
探讨

如果,a[i][0]和b[i][0]的范围已知,而且a[i][1]和b[i][1]都是正数的话,可以更简化
Java code
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的范围,可能考虑负数什么*/……