【发布时间】:2023-01-31 16:31:00
【问题描述】:
拼接是时间复杂度O(n); 我试过这个版本而不是拼接: 这增加了空间复杂性,但我认为时间复杂性较低。
let arr = [0,1];
arr[5] = 5;
// i need to push numbers into this index only-not to the whole array
// push wont work on a 1d array but will work on 2d array
arr[5] = [[], 5];
// now it is possible to push into this index
arr[5].push(15,125,1035);
// remove the unnecessary empty cell []
arr[5].shift();
console.log(arr) // result [0,1,[5,15,125,1035]]
那么这比 splice 更糟还是更好(就时间复杂度而言)?
编辑: 这是对给出的答案的错误理解,我的问题是我不明白为什么你不能推入数组的索引。 当你尝试: arr = [1,2,3,4] 然后 arr[1].push(2.5); 你会得到一个错误,因为你试图推入一个原语(数字而不是对象/数组)。 我的错误是我认为 JS 不允许这样做。
【问题讨论】:
-
你为什么说 push 不能在一维数组上工作?
let arr = [5]; arr.push(15,125,1035),它给出了相同的[5,15,125,1035]。 -
不好的例子,我会给你一个更好的数组版本。已编辑
-
为什么你一开始有一个空单元格?
-
阅读标题。尝试推入特定的一维数组索引。在 js 中不可能。只有拼接。
-
只要做
arr[5] = [5],然后你做arr[5].push(15,125,1035);。顺便说一句,你上面说的(“尝试并推入特定的一维数组索引。在 js 中是不可能的。只有拼接。”) 完全不正确。
标签: javascript arrays insert splice