天天看点

[LeetCode]565. Array Nesting

https://leetcode.com/problems/array-nesting/#/description

给一个长度N的数组,里面元素为1 ~ N - 1

找到最长的子数组

S[K] = { A[K], A[A[K]], A[A[A[K]]], ... }.

返回长度

从多个起点到达同一个值之后的路径都是完全相同的,所以每个值最多遍历一次,时间复杂度O(N),每次遍历到就加到set中

public class Solution {
    HashSet<Integer> set = new HashSet();
    public int arrayNesting(int[] nums) {
        int max = 0;
        for (int i = 0; i < nums.length; i++) {
            max = Math.max(max, check(nums, i));
        }
        return max;
    }
    private int check(int[] nums, int k) {
        int res = 0;
        while (!set.contains(k)) {
            set.add(k);
            k = nums[k];
            res++;
        }
        return res;
    }
}