也做了一下腾讯前端面试题
看到这个帖子:http://www.cnblogs.com/ilian/archive/2012/07/01/tx-test-entry.html
当时就想到了《编程珠玑》里讲到的 bitmap 算法。在 EditPlus 里敲了一下,实现如下:
<script>
// Array Remove - By John Resig (MIT Licensed)
Array.prototype.remove = function(from, to) {
var rest = this.slice((to || from) + 1 || this.length);
this.length = from < 0 ? this.length + from : from;
return this.push.apply(this, rest);
};
var arr = [];
for (var i = 0; i < 100000; i++)
arr[i] = i;
arr.remove(73501);
arr.remove(17);
arr.remove(2);
var t1 = new Date();
var bitmap = [];
//for (var i = 0; i < 12500; i++)
// bitmap[i] = 0;
for (var i = 0; i < arr.length; i++){
var x = arr[i];
var j = Math.floor(x / 8);
bitmap[j] = bitmap[j] | (0x80 >> (x % 8));
}
for (var x = 0; x < bitmap.length; x++){
var b = bitmap[x];
if (b == 255) continue;
for (var i = 0; i < 8; i++) {
if (((0x80 >> i) & b) == 0)
document.write("Found missing number: " + (x * 8 + i) + "<br/>");
}
}
var t2 = new Date();
document.write(t2 - t1);
</script>
Array.prototype.remove = function(from, to) {
var rest = this.slice((to || from) + 1 || this.length);
this.length = from < 0 ? this.length + from : from;
return this.push.apply(this, rest);
};
var arr = [];
for (var i = 0; i < 100000; i++)
arr[i] = i;
arr.remove(73501);
arr.remove(17);
arr.remove(2);
var t1 = new Date();
var bitmap = [];
//for (var i = 0; i < 12500; i++)
// bitmap[i] = 0;
for (var i = 0; i < arr.length; i++){
var x = arr[i];
var j = Math.floor(x / 8);
bitmap[j] = bitmap[j] | (0x80 >> (x % 8));
}
for (var x = 0; x < bitmap.length; x++){
var b = bitmap[x];
if (b == 255) continue;
for (var i = 0; i < 8; i++) {
if (((0x80 >> i) & b) == 0)
document.write("Found missing number: " + (x * 8 + i) + "<br/>");
}
}
var t2 = new Date();
document.write(t2 - t1);
</script>
原帖子里几个答案用到的类似方法貌似是直接分配的和原数组一样大的数组作为位图来查找,貌似比我这个空间上要浪费多7倍。我用的是二进制位存储。