实现一个函数:凑14

XX公司综合机试题第一题,以前有人讨论过,这里列出不同的算法

1. 请实现一个函数:凑14;输入很多个整数(1<=数值<=13),任意两个数相加等于14就可以从数组中删除这两个数, 求剩余数(按由小到大排列);比如:输入数组[9,1,9,7,5,13], 输出数组[7,9]


public static Integer[] doTest(Integer[] array, Integer num) {
int[] temp = new int[num];
for (int i = 0; i < array.length; i++) {
if (array[i] < 1 || array[i] >= num)
return null;
++temp[array[i]];
}
for (int i = 1; i < num / 2; i++) {
if (temp[i] > temp[num - i]) {
temp[i] -= temp[num - i];
temp[num - i] = 0;
} else {
temp[num - i] -= temp[i];
temp[i] = 0;
}
}
if (num % 2 == 0) {
temp[num / 2] = temp[num / 2] % 2;
}
List<Integer> resultList = new LinkedList<Integer>();
for (int i = 1; i < temp.length; i++) {
if (0 != temp[i]) {
for (int j = 0; j < temp[i]; j++) {
resultList.add(i);
}
}
}
if (resultList.size() > 0) {
Integer[] result = new Integer[resultList.size()];
for (int i = 0; i < resultList.size(); i++) {
result[i] = resultList.get(i);
}
return result;
} else
return null;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值