1. 程式人生 > >[LeetCode] 565. Array Nesting

[LeetCode] 565. Array Nesting

ext open space chm while relative for star sting

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

[LeetCode] 565. Array Nesting