只等公子 2022-05-04 13:54:14
(function () { const del = (arr, index, len) => { if (index < 0) { index = arr.length - Math.abs(index); } let i = index + len; let result = []; let count = len; let offset = index; while (count--) { result.push(arr[offset++]); } while (i < arr.length) { arr[i - len] = arr[i]; i++; } arr.length = arr.length - len; return result; } const insert = (arr, index, items) => { // arr.length = arr.length + items.length; let i = arr.length - 1; while (i >= index) { arr[i + items.length] = arr[i]; i--; } i = 0; while (i < items.length) { arr[i + index] = items[i]; i++ } } Array.prototype._splice = function _splice(index, deleteCount, ...rest) { let arr = this; let removed = []; // 只有一个元素 if (deleteCount === undefined) { removed = del(arr, index, arr.length - Math.abs(index)); } else { removed = del(arr, index, deleteCount); if (rest.length) { insert(arr, index, rest); } } return removed; } var myFish = ["angel", "clown", "mandarin", "sturgeon"]; var removed = myFish._splice(2, 0, "drum"); console.log(myFish, removed) // 运算后的 myFish: ["angel", "clown", "drum", "mandarin", "sturgeon"] // 被删除的元素: [], 没有元素被删除 var myFish = ['angel', 'clown', 'mandarin', 'sturgeon']; var removed = myFish._splice(2, 0, 'drum', 'guitar'); console.log(myFish, removed) // 运算后的 myFish: ["angel", "clown", "drum", "guitar", "mandarin", "sturgeon"] // 被删除的元素: [], 没有元素被删除 var myFish = ['angel', 'clown', 'drum', 'mandarin', 'sturgeon']; var removed = myFish._splice(3, 1); console.log(myFish, removed) // 运算后的 myFish: ["angel", "clown", "drum", "sturgeon"] // 被删除的元素: ["mandarin"] var myFish = ['angel', 'clown', 'drum', 'sturgeon']; var removed = myFish._splice(2, 1, "trumpet"); console.log(myFish, removed) // 运算后的 myFish: ["angel", "clown", "trumpet", "sturgeon"] // 被删除的元素: ["drum"] var myFish = ['angel', 'clown', 'trumpet', 'sturgeon']; var removed = myFish._splice(0, 2, 'parrot', 'anemone', 'blue'); console.log(myFish, removed) // 运算后的 myFish: ["parrot", "anemone", "blue", "trumpet", "sturgeon"] // 被删除的元素: ["angel", "clown"] var myFish = ['parrot', 'anemone', 'blue', 'trumpet', 'sturgeon']; var removed = myFish._splice(myFish.length - 3, 2); console.log(myFish, removed) // 运算后的 myFish: ["parrot", "anemone", "sturgeon"] // 被删除的元素: ["blue", "trumpet"] var myFish = ['angel', 'clown', 'mandarin', 'sturgeon']; var removed = myFish._splice(-2, 1); console.log(myFish, removed) // 运算后的 myFish: ["angel", "clown", "sturgeon"] // 被删除的元素: ["mandarin"] var myFish = ['angel', 'clown', 'mandarin', 'sturgeon']; var removed = myFish._splice(2); console.log(myFish, removed) // 运算后的 myFish: ["angel", "clown"] // 被删除的元素: ["mandarin", "sturgeon"] })()
- 共 1 页
- 1
没看懂你们的回答在答什么,原来的O(n^3)是怎样的,然后通过什么策略变成了O(n)的?
第 97 题:React 和 Vue 的 diff 时间复杂度从 O(n^3) 优化到 O(n) ,那么 O(n^3) 和 O(n) 是如何计算出来的?