华为面试题 题目:有两个数组a,b,大小都为n,数组元素的值任意,无序; 要求:通过交换a,b中的元素,使数组a元素的和与数组b元素的和之间的差最小

package com.yzh.test;


import java.util.ArrayList;
import java.util.Collections;
import java.util.List;


public class SortList {


public static void main(String[] args) {
List<Integer> a = new ArrayList<>();
a.add(1);
a.add(3);
a.add(4);
a.add(8);
System.out.println("sum(a):"+sum(a));
List<Integer> b = new ArrayList<>();
b.add(2);
b.add(6);
b.add(7);
b.add(5);
System.out.println("sum(b):"+sum(b));
List<Integer> ab = new ArrayList<>();
ab.addAll(a);
ab.addAll(b);
Collections.sort(ab);
System.out.println(ab.toString());
System.out.println("sum(ab):"+sum(ab));
a = new ArrayList<>();
b = new ArrayList<>();

int size = ab.size();
for(int i=0; i<size;i=i+2){
if(a.size()<1 && b.size()<1){
a.add(ab.get(i));
b.add(ab.get(i+1));
continue;
}
//集合的和大的先放小的数据
if(sum(a)>sum(b)){
a.add(ab.get(i));
b.add(ab.get(i+1));
continue;
//集合的和大的先放小的数据
}else if(sum(b)>sum(a)){
b.add(ab.get(i));
a.add(ab.get(i+1));
continue;
//一样大
}else{
a.add(ab.get(i));
b.add(ab.get(i+1));
continue;
}

}

int suma = sum(a);
int sumb = sum(b);

System.out.println(suma>sumb ? suma-sumb : sumb-suma);

}

public static int sum(List<Integer> list){
int sum=0;
for(int num : list){
sum+=num;
}
return sum;
}


}
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值