查找并返回 JavaScript 中集合的最长长度
问题
我们需要编写一个 JavaScript 函数,该函数将数字数组 arr 作为第一个也是唯一的参数。
长度为 N 的数组 arr 包含从 0 到 N-1 的所有整数。我们的函数应该查找并返回集合 S 的最长长度,其中 S[i] = {A[i], A[A[i]], A[A[A[i]]], ...} 受制于以下规则。
假设 S 中的第一个元素从索引 = i 的元素 A[i] 开始选择,则 S 中的下一个元素应该是 A[A[i]],然后是 A[A[A[i]]]…以此类推,我们在 S 中出现重复元素之前停止添加。
例如,如果函数的输入为:
const arr = [5, 4, 0, 3, 1, 6, 2];
则输出应为:
const output = 4;
输出解释
A[0] = 5, A[1] = 4, A[2] = 0, A[3] = 3, A[4] = 1, A[5] = 6, A[6] = 2.
最长的 S[K] 之一
S[0] = {A[0], A[5], A[6], A[2]} = {5, 6, 2, 0}示例
以下是代码:
const arr = [5, 4, 0, 3, 1, 6, 2];
const arrayNesting = (arr = []) => {
const visited = {}
const aux = (index) => {
if (visited[index]) {
return 0
}
visited[index] = true
return aux(arr[index], visited) + 1
}
let max = 0
arr.forEach((n, index) => {
if (!visited[index]) {
max = Math.max(max, aux(index))
}
)
return max
}
console.log(arrayNesting(arr));输出
以下是控制台输出:
4
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP