我有一个最大值:
var max = 666;
var check = 49;
在我的数学计算过程中,我将值对S推入像这样的二维数组
arr[i].push([a,b]);
但一切都很慢,我认为这是因为阵列非常庞大。我的arr就像这样
[ [ [ 1, 35 ],
[ 2, 39 ],
[ 3, 41 ],
[ 4, 42 ],
[ 5, 43 ],
[ 6, 44 ],
[ 7, 44 ],
[ 8, 45 ],
[ 9, 45 ],
[ 10, 45 ],
[ 11, 46 ],
[ 12, 46 ],
[ 13, 46 ],
[ 14, 46 ],
[ 15, 47 ],
[ 16, 47 ],
[ 17, 47 ],
[ 18, 47 ],
[ 19, 47 ],
[ 20, 48 ],
[ 21, 48 ],
[ 22, 48 ],
[ 23, 48 ],
[ 24, 48 ],
[ 25, 48 ],
[ 26, 48 ],
[ 27, 48 ],
[ 28, 49 ],
[ 29, 49 ],
[ 30, 49 ]]
因为你可以看到第一个元素是渐进元素,第二个元素来自calc,我的想法是:
仅推送不存在第二个元素的对(最多一个)
如果第二个元素等于check
var,我会推送第一个元素的max
var,第二个元素的check
var。停止
换句话说,这是预期的结果
[ [ [ 1, 35 ],
[ 2, 39 ],
[ 3, 41 ],
[ 4, 42 ],
[ 5, 43 ],
[ 7, 44 ],
[ 10, 45 ],
[ 14, 46 ],
[ 19, 47 ],
[ 27, 48 ],
[ 666, 49 ]]
有关如何尽可能快地制作它的任何想法?也许这不是问题所在,但我认为它越小越好,
Ĵ
答案 0 :(得分:0)
使用另一个数组来跟踪您已推送的值:
if (!(b in already_pushed)) {
if (b == check) {
arr[i].push([max, b]);
break;
} else {
already_pushed[b] = arr[i].length;
arr[i].push([a, b]);
}
} else if (a > already_pushed[b]) {
var index = already_pushed[b];
arr[i][index][0] = a;
}
}
完整代码:
var max = 666;
var check = 49;
var input = [
[1, 35],
[2, 39],
[3, 41],
[4, 42],
[5, 43],
[6, 44],
[7, 44],
[8, 45],
[9, 45],
[10, 45],
[11, 46],
[12, 46],
[13, 46],
[14, 46],
[15, 47],
[16, 47],
[17, 47],
[18, 47],
[19, 47],
[20, 48],
[21, 48],
[22, 48],
[23, 48],
[24, 48],
[25, 48],
[26, 48],
[27, 48],
[28, 49],
[29, 49],
[30, 49]
];
var arr = [
[]
];
var already_pushed = [];
var i = 0;
for (var j = 0; j < input.length; j++) {
var el = input[j];
var a = el[0],
b = el[1];
if (!(b in already_pushed)) {
if (b == check) {
arr[i].push([max, b]);
break;
} else {
already_pushed[b] = arr[i].length;
arr[i].push([a, b]);
}
} else if (a > already_pushed[b]) {
var index = already_pushed[b];
arr[i][index][0] = a;
}
}
console.log(arr);
&#13;