实现一个函数:凑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;
}

你可能感兴趣的:(java,算法)