【Leetcode 】565. 数组嵌套(Array Nesting)

    xiaoxiao2024-11-05  79

    Leetcode - 565 Array Nesting (Medium)

    题目描述:数组由 0 到 N - 1 的元素组成,找出最长的序列 S[i] = {A[i], A[A[i]], A[A[A[i]]], … }。

    Input: A = [5,4,0,3,1,6,2] Output: 4 Explanation: A[0] = 5, A[1] = 4, A[2] = 0, A[3] = 3, A[4] = 1, A[5] = 6, A[6] = 2. One of the longest S[K]: S[0] = {A[0], A[5], A[6], A[2]} = {5, 6, 2, 0}

    解题思路:由于每个路径都是循环的,所以已经访问过的就不必再访问了,长度一定是相同的。

    public int arrayNesting(int[] a) { int max = 0; for (int i = 0; i < a.length; i++) { int index = i, count = 0; while (a[index] != -1) { count++; int t= a[index]; a[index] = -1; index = t; } max = Math.max(max, count); } return max; }
    最新回复(0)