回答 华为面试题 8分钟写出代码

清华大佬耗费三个月吐血整理的几百G的资源,免费分享!....>>>

<div style="background-color:#000;color:#fff; padding:20px;">
<script type="text/javascript" language="javascript">   
function GetRandomNum(Min,Max){   
	var Range = Max - Min;    
	var Rand = Math.random();
	return(Min + Math.round(Rand * Range));   
}   

function GetRandomArray(Length){
	var arrayObj = new Array(Length);
	for(var i=0;i<Length;i++){
		arrayObj[i]=GetRandomNum(10,20);
	}
	return arrayObj;
}  

function sum(arguments){
	var r=0;
	for (var i=0;i<arguments.length;i++){
		r=arguments[i]+r;
	}
	return r;
}

function num(arguments){
	var r=0;
	for (var i=0;i<arguments.length;i++){
		if(arguments[i]){
			r++;
		}
	}
	return r;
}

//先创建A和B两个数组分别以随机数填充
var A = GetRandomArray(6);
var B = GetRandomArray(6);
//打印A和B数组
document.write("<br/>");
document.write("A:" + A.toString());
document.write("<br/>");
document.write("B:" + B.toString());
//将A和B两个数组进行合并排序
var AB = new Array(A.length+B.length);
for(var i=0;i<A.length;i++){
	AB[i]=A[i];
}
for(var i=0;i<B.length;i++){
	AB[A.length+i]=B[i];
}
//重置A和B数组
A = new Array();
B = new Array();
//打印A和B数组合并数组AB
//document.write("<br/>");
//document.write("AB:" + AB.toString());
//将AB数组进行排序
AB.sort();
//打印排序后的数组AB
document.write("<br/>");
document.write("AB:" + AB.toString());
//调用递归方法
CalAB(A,B,AB);
//反复填充递归方法定义
function CalAB(a,b,ab){
	if(ab.length==0){
		return;
	}

	if(num(a)==0){
		a.push(ab[ab.length-1]);
		ab.splice(ab.length-1,1);
	}else if(num(a)>num(b)){
		var tmp = sum(a)- sum(b);
		var tmpIndex=0;
		for(var i=0;i<ab.length;i++){
			if(Math.abs(ab[i]-tmp)<Math.abs(ab[tmpIndex]-tmp)){
				tmpIndex=i;
			}
		}

		b.push(ab[tmpIndex]);
		ab.splice(tmpIndex,1);
			
	} else if(num(a)==num(b)){
		 if(ab.length==2){
			if(sum(a)>sum(b)){
				if(ab[0]<ab[1]){
					a.push(ab[0]);
					b.push(ab[1]);
					ab.splice(0,2);
				}else{
					b.push(ab[0]);
					a.push(ab[1]);
					ab.splice(0,2);	
				}
			}else{
				if(ab[0]>ab[1]){
					a.push(ab[0]);
					b.push(ab[1]);
					ab.splice(0,2);
				}else{
					b.push(ab[0]);
					a.push(ab[1]);
					ab.splice(0,2);	
				}	
			}
		}
		else{
			var tmp = sum(a)- sum(b);
			var tmpIndex=0;
			for(var i=0;i<ab.length;i++){
				if(Math.abs(ab[i]-tmp)<Math.abs(ab[tmpIndex]-tmp)){
					tmpIndex=i;
				}
			}
			a.push(ab[tmpIndex]);
			ab.splice(tmpIndex,1);
		}
	}
	
	CalAB(A,B,AB);
}
document.write("<br/>=========================================<br/>");
document.write("A:" + A.toString());
document.write("<br/>");
document.write("B:" + B.toString());
document.write("<br/>");
document.write("D-value:" + Math.abs(sum(A)-sum(B)).toString());
document.write("<br/>&nbsp;");
</script>
</div>