Array Nesting
首先因为数值范围在0-(n-1)里面,所以这些数之间的跳动是必然成环的,只是这个环的大小问题而已,而这道题要我们求的结果正是这里面最大的环的长度,接着再思考一个问题,我们能不能从环上的任意一个点出发遍历一遍环同时得到这个环的长度?答案是可以的,因为环就意味着任意一个点都能作为起点,有了这个结论,我们就可以利用hashset做到在O(n)的时间复杂度下找到这个长度,每到一个环上某点,我们就直接把这个环遍历一遍,同时将遍历到的点全部踢出hashset,这样保证了我们只用遍历O(n)的结点就知道了最大环的长度
class Solution(object):
def arrayNesting(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
result = 0
checker = set(nums)
while checker:
start = checker.pop()
nxt = nums[start]
count = 1
while start != nxt:
checker.remove(nxt)
nxt = nums[nxt]
count += 1
result = max(count, result)
return result
另外这题还有空间复杂度O(1)的方法,暂时不研究了