一道数组分割题

有一个无序、元素个数为2n订的正整数数组,要求:如何能把这个数组分割成元素个数为n的两个数组,并使子数组的和最接近?

以下是我写的代码:

import java.util.ArrayList;
import java.util.Iterator;
import java.util.Scanner;

public class Main {

public static void main(String[] args) {
ArrayList heap[];
int num[],n,i,j,sum=0,temp;
Iterator it;
//读取数组元素
Scanner in = new Scanner(System.in);
n = in.nextInt();
num = new int[n+1];
heap = new ArrayList[n/2+1];//用来保存从数组中取i个元素所能产生的和
for(i=1;i<=n;i++){
num[i] = in.nextInt();
sum += num[i];
}
//初始化
heap[0] = new ArrayList();
heap[0].add(0);

for(i=1;i<=n;i++){
int j_max = i < n/2-1 ? i : n/2-1;

for(j=j_max;j>=0;j--){
if(heap[j] == null) heap[j] = new ArrayList();
it = heap[j].iterator();
while(it.hasNext()){
temp = (Integer)(it.next());
if(temp + num[i] < sum / 2){//只取和小于总和一般的数
if(heap[j+1] == null) heap[j+1] = new ArrayList();
heap[j+1].add(num[i] + temp);
}
}

}
}

it = heap[n/2].iterator();
int max = 0;
while(it.hasNext()){
temp = (Integer)it.next();
if(temp > max) max = temp;

}
System.out.println(max + ":" + (sum-max));
}

}



还有什么更好的方法吗?
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值