一个数组,有9998个不同的元素,这些元素的范围都在[1,10000]之间,求缺少的两个数

170 阅读1分钟

面试问道的一道题,当时说用数组进行操作,以及用快排进行操作面试官一直不满意。

面试官提醒注意限制条件[1,10000],突然想到将数组所有数相加,而后再用1-10000这些数的和减去这些数,即可得到缺少的两个数之和。

但是后面想不出来,今天试着将所有的数相乘,但是这种情况会出现上溢,

因而,将已知1-10000的数从最大开始除以数组的数,再相乘,最后即可求出缺少的两个数的乘积。

具体代码如下(应该效率不高):

	public static void main(String[] args) {
		int[] a = {1,4,9,10,5,8,6,3};
		int max = 10;
		int min = 1;
		double multiply = 1;
		int sum = 0;
		for(int i = 0; i < a.length; i ++) {
			sum += a[i];
			//防止越界溢出
			if(multiply / a[i] * max < 0) {
				multiply = multiply / a[i] * min ++;
			}else {
				multiply = multiply / a[i] * max --;
			}
		}
		//x * y = multiply;
		multiply = Math.ceil(multiply * min * max);
		//x + y = sum;
		sum = (1 + 10) * 10 / 2 - sum;
		//b^2 - 4ac
		double temp = sum * sum - 4 * multiply;
		temp = Math.sqrt(temp);
                //其实下面两个数不需要进行四舍五入,因为temp这步已经取整后,
                //最后得到的结果必行是整数
		int leave1 = (int)Math.round((sum - temp)/2);
		int leave2 = (int)Math.round((sum + temp)/2);
		System.out.println(leave1 + "\t" + leave2);
	}