我需要从给定数组中删除紧随其后的重复项
items
。
例如,如果我有这个数组:
[1, 2, 2, 3, 3, 1, 1, 4, 5, 5, 4, 4, 4, 6, 2]
...这就是结果应该是的:
[1, 2, 3, 1, 4, 5, 4, 6, 2]
如果我使用
[...new Set(items)]
,我就会得到一组独特的项目,这不是我想要的:
[1,2,3,4,5,6]
我怎样才能做到这一点(理想情况下,在 O(n) 时间内)?
function removeImmediateDuplicates(arr) {
const result = [];
const n = arr.length;
for (let i = 0; i < n; i++) {
if (arr[i] !== arr[i + 1]) {
result.push(arr[i]);
}
}
return result;
}
const items = [1, 2, 2, 3, 3, 1, 1, 4, 5, 5, 4, 4, 4, 6, 2];
const result = removeImmediateDuplicates(items);
console.log(result); // Output: [1, 2, 3, 1, 4, 5, 4, 6, 2]