我想要编写一个算法来删除重复的数组,并在javascript中用一个循环对数组进行排序。我想用算法而不是声明性的方法来实现它。我可以用单循环排序,但不能删除重复。如果有人帮我,我会很高兴的。
数组中的元素数为10^6,每个元素等于或大于0,小于300。
这是我的排序算法:
var a = [2, 7, 5, 1, 3, 2, 7];
for (let i = 0; i < a.length - 1; i++) {
if (a[i] > a[i + 1]) {
let temp = a[i]
a[i] = a[i + 1]
a[i + 1] = temp
i = -1
}
}
console.log(a)
发布于 2022-01-05 23:35:29
这是光荣的,你是足够好奇,试图找到一个解决办法,即使是在面试之后。对程序员来说是个好兆头。
我将使用一个对象从末尾跟踪任何duplicates.
current < previous
previous索引,或者
a中的位置。8,8在数组的末尾)
numberOfLoops只是因为它很有趣。
var a = [2, 2, -1, 8, 5, 1, 3, 3, 13, 2, 8, 8];
var temp = {}; // 1
var result = [];
var current, previous;
var numberOfLoops = 0;
for (let i = a.length - 1; i > 0 ; i--) { // 2
current = a[i];
previous = a[i - 1];
numberOfLoops++; // 8
if (temp.hasOwnProperty(previous) || // 5
current == previous) { // 6
a.splice(i - 1, 1); // 7
// i++;
} else if (current < previous) { // 3
a[i - 1] = current;
a[i] = previous;
i += 2;
delete temp[current];
} else { // 4
temp[current] = current;
}
}
console.log({numberOfLoops}); // 23
console.log(a); // [-1, 1, 2, 3, 5, 8, 13]
https://stackoverflow.com/questions/70592691
复制相似问题