/* 两个数值a,b元素数都为n,使a,b数组重新组合,
使a数组各元素的和与b数组各元素的和只差最小.
思路: 先将a,b数组组合成c数组,c数组排序后,a取c数组两头,b取c数组中间.
排序后首位相加最接近,所以差最小
看不明白的地方可以回复.
*/
class Dome2 {
public static final int MIUI = 520;
public static void main(String[] args) {
int[] arr = {1,5,3,4,2,9};
int[] brr = {6,7,1,9,8,4};
int[] crr =new int[12];
for (int i = 0;i < crr.length/2 ;i++ ) {
crr[i] = arr[i];
}
for (int i = arr.length;i < crr.length ; i++) {
crr[i] = brr[i-arr.length];
}
for (int i = 0;i < crr.length ;i++ ) { //冒泡排序法
for (int j = 0;j < crr.length-1;j++ ) {
if (crr[j]<crr[j+1]) {
int temp = crr[j];
crr[j] = crr[j+1];
crr[j+1] = temp;
}
}
}
for (int i = 0;i < crr.length ;i++ ) { //重组数组,a数组取c数组两头,b取c数组中间
if (i <= 2) {
arr[i] = crr[i];
}else if (i>=3 && i <=8) {
brr[i-3] = crr[i];
}else {
arr[i-6] = crr[i];
}
}
String stra="{";
for (int i = 0;i < arr.length ;i++ ) { //输出a数组
if (i==arr.length-1) {
stra+=arr[i] + "}";
}else {
stra+=arr[i]+", ";
}
}
System.out.println("a数组为: " + stra + "\n");
String strb="{";
for (int i = 0;i < brr.length ;i++ ) { //输出b数组
if (i==brr.length-1) {
strb+=brr[i] + "}";
}else {
strb+=brr[i]+", ";
}
}
System.out.println("b数组为: " + strb);
}
}
|
|