今天百度了一下腾讯的前端面试题,找了好久只有找到这道题,顺便mark一下
题目是这样的:有一组数字,从1到n,从中减少了3个数,顺序也被打乱,放在一个n-3的数组里,请找出丢失的数字,最好能有程序,最好算法比较快。
网上的答案有一些出入,整理如下
1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 2 <html xmlns="http://www.w3.org/1999/xhtml"> 3 4 <head> 5 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 6 <title> 7 腾讯的JS前端面试题 8 </title> 9 <script> 10 var ary = [1, 5, 7, 6, 4, 8, 10]; 11 var n = ary.length + 3; 12 var newAry = []; 13 document.write("假设n=" + n + "<br/>"); 14 ary.sort(function(a, b) { 15 return a - b; 16 }); 17 document.write("初始数组:" + ary + "<br/>"); 18 for (var i = 1, 19 j = 0; i <= n; i++, j++) { 20 var diff = ary[j] - i; 21 if (diff > 0) { 22 for (var k = 0; k < diff; k++) { 23 newAry.push(i++); 24 25 } 26 } 27 } 28 //alert(newAry); 29 document.writeln("缺少的数:" + newAry); 30 </script> 31 </head> 32 33 <body> 34 </body> 35 36 </html>