博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
通过交换a,b中的元素,使[序列a元素的和]与[序列b元素的和]之间的差最小(两数组的差最小)。...
阅读量:6033 次
发布时间:2019-06-20

本文共 2536 字,大约阅读时间需要 8 分钟。

hot3.png

import java.util.ArrayList;import java.util.List;public class LeastSumDiff {	public static void main(String args[]) {		int[] a1 = { 100, 99, 98, 1, 2, 3 };		// int[] a1 = { 40, 50 };		int[] a2 = { 1, 2, 3, 4, 5, 40 };		// int[] a2 = { 20, 15 };//		int a1[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 90, 0, 0, 100 };//		int a2[] = { -1, -2, -100, -3, 99, -222, -2, -3, -5, -88, 11, 12, 13 };		//int leastSum = leastSumDiff(a1, a2);		int leastSum = leastSumDiff1(a1, a2);		for (int i : a1) {			System.out.print(i + " ");		}		System.out.println();		for (int i : a2) {			System.out.print(i + " ");		}		System.out.println();		System.out.println(leastSum);	}	public static int leastSumDiff(int[] a1, int[] a2) {		int leastSum = 0;		int sumA = 0;		int sumB = 0;		for (int i = 0; i < a1.length; i++) {			sumA += a1[i];			sumB += a2[i];		}		leastSum = Math.abs(sumA - sumB);		for (int i = 0; i < a1.length; i++) {			for (int j = 0; j < a2.length; j++) {				int tmp = sumA + a2[j] - a1[i];				int tmp1 = sumB + a1[i] - a2[j];				int tmpLeast = Math.abs(tmp - tmp1);				if (leastSum > tmpLeast) {					int tmpa1 = a1[i];					a1[i] = a2[j];					a2[j] = tmpa1;					sumA = tmp;					sumB = tmp1;					leastSum = tmpLeast;					if (tmpLeast == 0) {						return 0;					}				}			}		}		return leastSum;	}	// a[i] - b[j] is around (sumA - sumB)/2;	public static int leastSumDiff1(int[] a, int[] b) {		int leastSum = 0;		int sumA = 0;		int sumB = 0;		for (int i = 0; i < a.length; i++) {			sumA += a[i];			sumB += b[i];		}		leastSum = Math.abs(sumA - sumB);		int nextToLeastSum = leastSum;		int tmpJ = 0;		List
aL = new ArrayList
(); List
bL = new ArrayList
(); for (int i = 0; i < a.length; i++) { boolean found = false; for (int j = 0; j < b.length; j++) { int currentGap = Math.abs(a[i] - b[j]) * 2; if (leastSum >= Math.abs(a[i] - b[j]) * 2) { if (!(leastSum > Math.abs(sumA - a[i] + b[j] - (sumB + a[i] - b[j])))) { continue; } if (!found) { nextToLeastSum = currentGap; tmpJ = j; found = true; } else { if (nextToLeastSum < currentGap) { nextToLeastSum = currentGap; tmpJ = j; } } } } if (found) { sumA = sumA - a[i] + b[tmpJ]; sumB = sumB + a[i] - b[tmpJ]; leastSum = Math.abs(sumA - sumB); int tmpa1 = a[i]; a[i] = b[tmpJ]; b[tmpJ] = tmpa1; nextToLeastSum = leastSum; } if (leastSum == 0) { return 0; } } return leastSum; }}

转载于:https://my.oschina.net/u/138995/blog/308710

你可能感兴趣的文章
【深入浅出Node.js系列二】Node.js&NPM的安装与配置
查看>>
没有学位,他通过以下四步进入Google
查看>>
linux系统定制-LFS-( 一 )
查看>>
YUM命令使用
查看>>
033_3
查看>>
nmon 监控软件
查看>>
Java虚拟机(JVM)中的内存设置详解
查看>>
extmail显示天气预报
查看>>
vlan
查看>>
俄罗斯方块总结
查看>>
编译cdh的spark,使得支持spark-sql
查看>>
PowerShell查询AD域内长期没有登录的计算机对象
查看>>
CDH使用之CM 5.3.x安装
查看>>
Linux学习之CentOS(九)--Linux系统的网络环境配置
查看>>
这个季节的忧伤,点到为止
查看>>
Nginx perl cgi 支持
查看>>
CephFS 文件系统应用
查看>>
J2EE集群
查看>>
mysqldump学习
查看>>
mysql通过配置文件进行优化
查看>>