在 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