565. Array Nesting
这道题目的大概意思是,先选定数组中一个起始的位置,再根据她的值定位到相应的下标,继续下去,直到出现循环为止,最后找出最长的不循环的。
显然需要将数组中每个位置起始的都要计算一遍,所以首先想到的就是dfs。
class Solution(object):
def arrayNesting(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if not nums:
return 0
visited = {}
result = 0
for idx in range(0, len(nums)):
if idx not in visited:
result = max(result, self.helper(nums, idx, visited))
return result
def helper(self, nums, start, visited):
"""
递归移动到下一个位置,直到和起始位置一样的时候
同时记录移动的个数
:param nums:
:param start:
:param visited:
:return:
"""
i = start
cnt = 0
while i != start or cnt == 0:
visited[i] = True
i = nums[i]
cnt += 1
return cnt
或者是不用函数递归的形式,直接写在一个函数里面,这样还避免了函数递归造成的消耗;
class Solution(object):
def arrayNesting(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
visited = [False] * len(nums)
max_cnt = 0
for i in range(len(nums)):
cnt = 1
first = i
if not visited[i]:
next_idx = nums[i] # 下一个位置
# dfs
while first != next_idx:
visited[next_idx] = True
next_idx = nums[next_idx]
cnt += 1
max_cnt = max(max_cnt, cnt)
return max_cnt