写点什么

LeetCode 565: Array Nesting

用户头像
隔壁小王
关注
发布于: 2020 年 05 月 07 日
LeetCode 565: Array Nesting

Description

A zero-indexed array A of length N contains all integers from 0 to N-1.

Find and return the longest length of set S, where S[i] = {A[i], A[A[i]], A[A[A[i]]], ... } subjected to the rule below.



Suppose the first element in S starts with the selection of element A[i] of index = i, the next element in S should be A[A[i]], and then A[A[A[i]]]… By that analogy, we stop adding right before a duplicate element occurs in S.

Example

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}



问题分析

  1. 按照题意,数组中的N个元素已按照其数值关系,被划分为1个或多个互不相交的“闭环”



  1. 本题要做的,就是依次找出所有的闭环,并返回环的最大长度

  2. 因此,可通过DFS解决该问题。其中每个节点均只有确定的一个子节点,仅需依次遍历至再次回到起点。一次遍历过程将遍历一个环上的全部节点。

  3. 遍历完所有的环,返回最大长度,即可。

实现要点

  1. 避免重复遍历:使用0/1数组,记录遍历状态;

Submission

class Solution:
def arrayNesting(self, nums: List[int]) -> int:
n = len(nums)
# dp[i] = 0 means node needs to be traversed
# dp[i] = 1 means node has been traversed
dp = [0 for i in range(n)]
res = 0
# do dfs
start = 0
while(start < n):
if(dp[start] == 1):
start = start + 1
continue
dp[start] = 1
tmp = 1
cur = nums[start]
while(cur != start):
tmp = tmp + 1
dp[cur] = 1
cur = nums[cur]
res = max(res, tmp)
start = start + 1
return res



发布于: 2020 年 05 月 07 日阅读数: 44
用户头像

隔壁小王

关注

还未添加个人签名 2020.04.29 加入

还未添加个人简介

评论

发布
暂无评论
LeetCode 565: Array Nesting