查找数组中的重复序列

问题描述 投票:0回答:1

我遇到了一个问题,尝试了很多解决方案,但没有一个有效。给定一个数字数组 [3, 2, 16, 16, 15, 1, 2, 16, 16, 16, 15, 1, 2],我想发现这个数组中的重复序列。

预期输出应为 [16, 16, 15, 1, 2]。

javascript arrays algorithm data-structures sequence
1个回答
0
投票

您可以使用 2 组来记住遇到的和重复的数字:

const arr = [3, 2, 16, 16, 15, 1, 2, 16, 16, 16, 15, 1, 2];
const found = new Set, repeated = new Set;
const result =  arr.reduce((r, n) => (repeated.has(n) || found.has(n) && repeated.add(n) && r.push(n) || found.add(n), r), []);
console.log(result);

© www.soinside.com 2019 - 2024. All rights reserved.