565. Array Nesting
The general meaning of this question is to first select a starting position in the array, and then locate the corresponding subscript according to her value, continue until a loop occurs, and finally find the longest non-loop.
Obviously, it is necessary to calculate the beginning of each position in the array, so the first thing that comes to mind is dfs.
class Solution(object):defarrayNesting(self, nums):""" :type nums: List[int] :rtype: int """ifnotnums:return0visited = {}result = 0foridxinrange(0, len(nums)):ifidxnotinvisited:result = max(
result , self . helper ( nums , idx , visited )) return result def helper ( self , nums , start , visited ): """ Recursively move to the next position until it is the same as the starting position and record the moving Number of :param nums: :param start: :param visited: :return: """ i = start cnt = 0 while i ! = start
or cnt == 0:visited[i] = Truei = nums[i]cnt += 1returncnt
Or write it directly in a function without function recursion, which also avoids the consumption caused by function recursion;
class Solution(object):defarrayNesting(self, nums):""" :type nums: List[int] :rtype: int """visited = [False] *len(nums)max_cnt = 0foriinrange(len(nums)):cnt = 1first = iifnotvisited[i]:
next_idx = nums[i] # 下一个位置# dfswhilefirst!= next_idx:visited[next_idx] = Truenext_idx = nums[next_idx]cnt += 1max_cnt = max(max_cnt, cnt)returnmax_cnt