【发布时间】:2019-12-23 20:17:44
【问题描述】:
我想按他的索引对数组进行排序。
看下面的代码:
var distances = [530, 0, 24, 335, 274, 591];
console.log(sortIndex(distances));
function sortIndex(toSort) {
return toSort.map(
(e,i) => {return {index: i, value: e};}
).sort(
(a,b) => a.value - b.value
).map(
(e,i) => {return e.index;},[]
);
}
输出是:
[1, 2, 4, 3, 0, 5]
谁能告诉我如何降低这个 sn-p 的复杂性?这个算法是O(n^3),不知道你能不能用更好的方案解决同样的问题?
外面有人吗?谢谢。
【问题讨论】:
-
该算法没有
O(n^3)复杂度。它具有O((n) + (n log n) + (n)) = O(n log n)的复杂性。第一个map是O(n),排序是O(n log n),最后的映射是O(n)。当我们将这些步骤加在一起时,剩下的复杂度是n log n。
标签: arrays algorithm sorting indexing time-complexity