对模糊的标题表示歉意,还不确定是否还能用其他方式来描述问题。
我最近遇到一种情况,我必须遍历对象数组以比较多个值,因此我选择在for循环中使用for循环来比较每个对象与其他每个对象。
尽管这在小型阵列上可以正常工作,但是一旦我的阵列变大(例如10,000个对象),性能就会成为一个大问题。
此数组包含以下类型的对象:
[{ char: '_', from: 0, to: 2, chrLength: 2 },
{ char: '_', from: 0, to: 7, chrLength: 7 },
{ char: 'a', from: 1, to: 3, chrLength: 2 },
{ char: 'a', from: 1, to: 6, chrLength: 5 },
{ char: '_', from: 2, to: 7, chrLength: 5 },
{ char: 'a', from: 3, to: 6, chrLength: 3 }]
我的想法是,我只能选择from
和to
之间不与任何其他对象重叠的对象。(from
并且to
是另一个数组中的索引)
因此,对于示例数组,可能的结果将是:
[{ char: '_', from: 0, to: 2, chrLength: 2 },
{ char: 'a', from: 1, to: 3, chrLength: 2 },
{ char: 'a', from: 1, to: 6, chrLength: 5 },
{ char: 'a', from: 3, to: 6, chrLength: 3 }]
我的处理方式如下:
var canUse = true,
posibilities = [];
for(i = 0; i < l; i++) {
canUse = true;
for(var j = 0; j < l; j++) {
if((results[i].from < results[j].from && results[i].to > results[j].to)) {
canUse = false;
break;
}
}
if(canUse) posibilities.push(results[i]);
}
看到较大的阵列的性能非常糟糕,我想知道是否有更好的解决方案?
这是想法(Demo):
(from + to)/2
。k
项目“插入”到树中并准备插入k+1
。您的步骤是:k+1
覆盖根-忽略它。k+1
根目录覆盖了-从树中删除根目录,然后再尝试一次。k+1
的中部和根的中部,继续到左或右子树。码
function process() {
console.log('Processing results of length: ' + l);
console.time('Processing');
var comparator = function(a, b) { //Comparator to build a tree
return a.mid - b.mid;
},
isAinB = function(a, b) { //util function to check if a is inside b
return b.from < a.from && b.to > a.to;
},
rbtree = new RBTree(comparator), //Build an empty tree
i = results.length - 1, item, posibilities = [];
function check(root, x) { //Recursive checker
var data;
if(!root) { //Either tree is empty or we've reached a leaf
rbtree.insert(x);
return;
}
data = root.data;
if(isAinB(data, x)) { //4
return;
}
if(isAinB(x, data)) { //5
rbtree.remove(data);
check(rbtree._root, x);
return;
}
check(root[comparator(data, x) > 0 ? 'left' : 'right'], x); //6
}
for(; i >= 0; i--) {
item = results[i];
item.mid = (item.from + item.to)/2; //2
check(rbtree._root, item); //3
}
rbtree.each(function(item) { //7
posibilities.push(item);
});
console.timeEnd('Processing');
console.log(posibilities.length);
}
顺便说一句,我已经使用了RBTree实现。不知道这是否是最好的:)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句