不知道来源的题目1

不知道来源的题目1

题目

有两个数组 A、B,长度都为 N,值为任意整数,无序,要求,通过交换 A、B 中的元素,使得 A 数组元素之和与 B 数组元素之和之间的差值最小。完成代码的同时,写出数组 [100,99,98,1,2, 3]和[1,2,3,4,5,40]交换后的结果。

思路

解法多种多样,但是我真没想出来什么特别合适的,采用了一种比较繁琐的方法。
首先计算两个数组的差值,之后尝试交换,只要能让差值减小,就交换,一直到没有这种可能性再结束,理论上这就是要的答案。

代码

  public static void change(int[] a, int[] b, int n, int before) {
    for (int i = 0; i < n; i++) {
      for (int j = 0; j < n; j++) {
        int after = before - 2 * (a[i] - b[j]);
        if (Math.abs(after) < Math.abs(before)) {
          int temp = a[i];
          a[i] = b[j];
          b[j] = temp;
          change(a, b, n, after);
          return;
        }
      }
    }
  }


  public static void main(String[] args) {
    int[] a = new int[]{100, 99, 98, 1, 2, 3};
    int[] b = new int[]{1, 2, 3, 4, 5, 40};
    int suma = 0;
    int sumb = 0;
    int len = a.length;
    for (int i = 0; i < len; i++) {
      suma += a[i];
      sumb += b[i];
    }
    change(a, b, len, Math.abs(suma - sumb));
    for (int i = 0; i < len; i++) {
      System.out.print(a[i] + " ");
    }
    System.out.println();
    for (int i = 0; i < len; i++) {
      System.out.print(b[i] + " ");
    }
  }
原文地址:https://www.cnblogs.com/blogxjc/p/12346865.html