【LeetCode】565. 数组嵌套

题目

565. 数组嵌套

索引从0开始长度为N的数组A,包含0N - 1的所有整数。找到最大的集合S并返回其大小,其中 S[i] = {A[i], A[A[i]], A[A[A[i]]], ... }且遵守以下的规则。

假设选择索引为i的元素A[i]S的第一个元素,S的下一个元素应该是A[A[i]],之后是A[A[A[i]]]... 以此类推,不断添加直到S出现重复的元素。

示例 1:

输入: A = [5,4,0,3,1,6,2]
输出: 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}

提示:

  1. N[1, 20,000]之间的整数。
  2. A中不含有重复的元素。
  3. A中的元素大小在[0, N-1]之间。

题解1(TLE)

思路

  • 暴力深搜所有情况,求取最大值

代码

class Solution:
    def arrayNesting(self, nums: List[int]) -> int:
        maxDepth = -1
        def dfs(n: int, visited: set, depth: int):
            nonlocal maxDepth
            if n not in visited:
                visited.add(n)
                dfs(nums[n], visited, depth+1)
            maxDepth = max(maxDepth, depth)
        for n in nums:
            dfs(n,set(),0)
        return maxDepth

复杂度

  • 时间复杂度: O ( n 2 ) O(n^2) O(n2)
  • 空间复杂度: O ( n ) O(n) O(n)

题解2(TLE)

思路

  • 相对于题解1,使用尾递归进行优化

代码

class Solution:
    def arrayNesting(self, nums: List[int]) -> int:
        maxDepth = -1
        def dfs(n: int, visited: set):
            if n not in visited:
                visited.add(n)
                return dfs(nums[n], visited) + 1
            else: return 0  
        for n in nums:
            maxDepth = max(maxDepth, dfs(n,set())) 

        return maxDepth

复杂度

  • 时间复杂度: O ( n 2 ) O(n^2) O(n2)
  • 空间复杂度: O ( n ) O(n) O(n)

题解3

思路

  • 该题相当于将所有的数作为节点,形成的图寻找最大的环的长度
  • 因为所有结点的出度为1,所以访问过的节点无需重新访问

代码

class Solution:
    def arrayNesting(self, nums: List[int]) -> int:
        res = 0
        visited = [False] * len(nums)
        for i in range(len(nums)):
            count = 0
            while not visited[i]:
                visited[i] = True
                i = nums[i]
                count += 1
            res = max(res, count)
        return res

复杂度

  • 时间复杂度: O ( n ) O(n) O(n)
  • 空间复杂度: O ( n ) O(n) O(n)

题解4

思路

  • 因为每个节点至多只访问一次,所以将是否访问过的信息保存在原数组当中 标记为-1

代码

class Solution:
    def arrayNesting(self, nums: List[int]) -> int:
        res = 0
        for i in range(len(nums)):
            count = 0
            while nums[i] != -1:
                tempN = nums[i]
                nums[i] = -1
                i = tempN
                count += 1
            res = max(res, count)
        return res

复杂度

  • 时间复杂度: O ( n ) O(n) O(n)
  • 空间复杂度: O ( 1 ) O(1) O(1)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

pass night

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值